虚函数使用的条件:
继承,virtual指定函数,父类指针或引用指向子类对象的地址
其中父类的析构函数需要为virtual,保证了内存的正确释放。
/*
设计一个汽车类vehicle,它有一个两个参数的构造函数,车轮数量wheels和车重量weights,
小汽车car类继承汽车类,其成员变量为passengers;开车类truck,成员变量:passengers和负载payload
*/
#include<iostream>
using namespace std;
class vehicle
{
private:
int wheels;
protected:
int weights;//子类可以使用
public:
vehicle(int wheels, int weights) :wheels(wheels), weights(weights)
{
cout << "This is vehicle" << endl;
}
virtual ~vehicle()
{
cout << "This is desconstruct vehicle" << endl;
}
virtual void show()const;
};
void vehicle::show() const
{
cout << "vehicle has " << wheels << "wheels and the weights of vehicle is " << weights << endl;
}
class car :public vehicle
{
private:
int passengers;
public:
car(int passengers, int weights, int wheels) :passengers(passengers), vehicle(wheels,weights)
{
cout << "This is car" << endl;
}
~car()
{
cout << "This is car desconstruction" << endl;
}
void show() const
{
vehicle::show();
cout << "car can take " << passengers << " passengers"<< endl;
}
};
class truck :public vehicle
{
private:
int passengers;
int payload;
public:
truck(int passengers, int payload, int wheels,int weights) :passengers(passengers), payload(payload), vehicle(wheels, weights)
{
cout << "This is truck" << endl;
}
~truck()
{
cout << "This is desconstruction truck" << endl;
}
void show() const
{
vehicle::show();
cout << "truck can take " << passengers << "passengers,and the payload is " << payload << endl;
}
};
int main()
{
vehicle *v = NULL;
car c(5,1000,4);
truck t(3,5000,4,2000);
v = &c;
v->show();
v = &t;
v->show();
return 0;
}