c++ inheritance not recognized
Is there some so开发者_Python百科lution or I have to keep exactly class types?
//header file
Class Car {
public:
Car();
virtual ~Car();
};
class Bmw:Car {
public:
Bmw();
virtual ~Bmw();
};
void Start(Car& mycar) {};
//cpp file
Car::Car(){}
Car::~Car() {}
Bmw::Bmw()
:Car::Car(){}
Bmw::~Bmw() {}
int main() {
Car myCar;
Bmw myBmw;
Start(myCar); //works
Start(myBmw); //!! doesnt work
return 0;
}
C++ defaults to private inheritance, so, you need to declare Bmw as:
class Bmw:public Car
Also, to be completely accurate, you should really have Start
as a virtual method of Car
and override it as needed in descendant classes. :)
You should write class Bmw : public Car
.
What you want to have here is public inheritance, but not a private one (which is default for classes in C++
).
You have Bmw
inheriting privately from Car
, which prevents converting a Bmw
reference to a Car
reference. Change the definition to:
class Bmw : public Car
You need public inheritance - it represents IS A relationship between derived and base types. As in bmw IS A car, while private inheritance (the default when not explicitly specified and what you have here) represents implemented in terms of relationship.
Try:
class Bmw: public Car
{
// ...
];
I'm no mechanic, but class Bmw: public Car
should fix you up and have you on the road to understanding inheritance in no time!
Inheritance is private
by default for class
es (public
for struct
s).
精彩评论