总结一点C++的知识

1.析构函数是可以显式调用的。

2.new也可以用来动态开辟有虚函数的类。


class Foo
{
public:
 virtual ~Foo() {cout<<"the destructor of Foo"<<endl;}
 virtual void display() const { cout<<"display class Foo"<<endl; }
private:
 int x_;
};

class Child: public Foo
{
public:
 virtual ~Child() {cout<<"the destructor of Child"<<endl;}
 void display() const {cout<<"display class Child"<<endl;}
private:
 int y_;
};

int main()

{

 cout<<sizeof(Foo)<<endl;  //8
 cout<<sizeof(Child)<<endl; //12
 cout<<endl;

 Foo* fp = new Foo; 
 fp->display();                        // display class Foo
 cout<<sizeof(*fp)<<endl;      // 8
 fp->~Foo();                         // the destructor of Foo
 cout<<endl;

 
 Foo* fc = new Child;             

 fc->display();                        // display class Child
 cout<<sizeof(*fc)<<endl;      // 8!!! 因为fc为Foo类型的指针,所以解引用出来的大小为Foo类的大小
 fc->~Foo();                        // the destructor of Child, the destructor of Foo
 cout<<endl;
 
 Child* fcc = new Child;          
 fcc->display();                     // display class Child
 cout<<sizeof(*fcc)<<endl;    // 12
 fcc->~Child();                      // the destructor of Child, the destructor of Foo
 cout<<endl;

 delete fp;                            // 调用析构函数。。。。。。
 delete fc;
 delete fcc;
 fp = fc = fcc = NULL;

}

原文地址:https://www.cnblogs.com/kex1n/p/1646832.html