总结一点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/archive/2010/01/13/1646832.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    总结一点C++的知识

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/6743

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月6日 下午3:19
下一篇 2023年2月6日 下午3:21

相关推荐