优先使用组合的方式,而不是继承
class AbstractCar{
public:
virtual void run() = 0;
};
class BMW:public AbstractCar{
public:
void run()override{
cout << "BMW run" << endl;
}
};
class DaZhong:public AbstractCar{
public:
void run()override{
cout << "DaZhong run" << endl;
}
};
#if 0
// 错误的做法
class Person : public BMW{
public:
void drive(){
run();
}
};
void test1(){
Person p;
p.drive();
}
#endif
// 正确做法
class Person{
public:
Person(){
car = nullptr;
}
Person(AbstractCar* c){
car = c;
}
void drive(){
car->run();
delete car;
}
void drive(AbstractCar* car){
car->run();
delete car;
}
private:
AbstractCar* car;
};
void test2(){
// 方式一:
Person* p = new Person(new BMW);
p->drive();
delete p;
p = new Person(new DaZhong);
p->drive();
delete p;
// 方式二:
Person pp;
pp.drive(new BMW);
pp.drive(new DaZhong);
}
int main()
{
test2();
return 0;
}