#include <iostream>
using namespace std;
class Point
{
public:
Point(double a = 0, double b = 0)
{
x = a;
y = b;
}
~Point(){ cout << "Executing Point destructor \n";}
private:
double x;
double y;
};
class Circle: public Point
{
public:
Circle(double a=0, double b=0, double c=0):Point(a,b), radius(c){}
~Circle(){cout<<"executing Circle destructor"<<endl;}
private:
double radius;
};
int main()
{
Point * p = new Circle(1, 1, 4);
delete p;
return 0;
}
执行的结果是:
Executing Point destructor
但我把派生类的构造函数:
Circle(double a=0, double b=0, double c=0):Point(a,b), radius(c){}
改成
Circle(double a=0, double b=0, double c=0)
{
Point(a,b);
radius = c;
}
运行结果是:
Executing Point destructor
Executing Point destructor
为什么第二种构造函数的方式,运行结果会多显示一行呢?
You can only initialize the base class with parameters in the colon after the constructor (called the initialization list).
You cannot write this in the constructor body (because when the function body starts to be executed, the base class has already completed the construction). What you write is actually equivalent to constructing a temporary object on the stack, which will be destroyed after the function returns, so there are more One line of output.
Class members (radius) can be written in two ways. They can be initialized in the initialization list or assigned in the function body. The former has higher execution efficiency (without considering optimization).
In addition, there is also a problem with the usage in your main function. If you want to use the pointer of the base class to store the derived class object, then you need to declare the destructor of the base class as virtual, otherwise it will appear when deleting. Memory leak.