虚函数使用意义:通过基类访问派生类定义的函数。
#include <iostream>
class fruit
{
private:
/* data */
public:
fruit(/* args */);
virtual ~fruit();
virtual void print() {std::cout << "this fruit print " << std::endl;}
};
fruit::fruit(/* args */)
{
}
fruit::~fruit()
{
std::cout << "fruit ~~" << std::endl;
}
class shape
{
private:
/* data */
public:
shape(/* args */);
~shape();
void print() {std::cout << "this shape print " << std::endl;}
};
shape::shape(/* args */)
{
}
shape::~shape()
{
std::cout << "shape ~~" << std::endl;
}
class apple : public fruit
{
private:
/* data */
public:
apple(/* args */);
~apple();
void print() {std::cout << "this apple print " << std::endl;}
};
apple::apple(/* args */)
{
}
apple::~apple()
{
std::cout << "apple ~~" << std::endl;
}
class circle :public shape
{
private:
/* data */
public:
circle(/* args */);
~circle();
void print() {std::cout << "this circle print " << std::endl;}
};
circle ::circle(/* args */)
{
}
circle ::~circle()
{
std::cout << "circle ~~" << std::endl;
}
int main()
{
apple *pApple = new apple;
// cout << "---" << endl;
pApple->print();
delete pApple;
std::cout << std::endl;
fruit *pfruit = new apple;
pfruit->print();
delete pfruit;
std::cout << std::endl;
circle *pCircle = new circle;
pCircle->print();
delete pCircle;
std::cout << std::endl;
shape *pshape = new circle;
pshape->print();
delete pshape;
return 0;
}
运行结果:
this apple print
apple ~~
fruit ~~
this apple print
apple ~~
fruit ~~
this circle print
circle ~~
shape ~~
this shape print
shape ~~
参考文章: