Tim*_*Tim 3 c++ oop inheritance
我可以Vehicle::color从Sedan类中访问的唯一方法是重新实现getter方法.我想从子类访问它,而不这样做.
// Base Class
class Vehicle
{
protected:
bool windowIsOpen[4];
int wheels;
char *color;
public:
Vehicle(char *color) : color(color){};
char *getColor() { return color; }
};
class Sedan : Vehicle
{
public:
Sedan(char* color) : Vehicle(color) {}
};
int main(int argc, char **argv){
Sedan se("green");
cout<<se.getColor()<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在定义你的课时,你写了class Sedan : Vehicle.这实际上和class Sedan : private Vehicle.换句话说,Vehicle是一个不向Sedan用户公开的实现细节.要进行这种公共继承,你应该写class Sedan : public Vehicle.
| 归档时间: |
|
| 查看次数: |
260 次 |
| 最近记录: |