zoukankan      html  css  js  c++  java
  • 总结一点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;

    }

  • 相关阅读:
    bzoj 3122 [Sdoi2013]随机数生成器(逆元,BSGS)
    归并排序
    MS-coco数据集下载及使用(转)
    转-深度学习视觉领域常用数据集汇总
    opencv-Mat数据类型及位数总结
    opencv-图像类型、深度、通道
    opencv-VS2010配置opencv2.4.8
    opencv-访问Mat中每个像素的值
    VS2010文件包含
    转载: 8个月从CS菜鸟到拿到Google Offer的经历+内推
  • 原文地址:https://www.cnblogs.com/kex1n/p/1646832.html
Copyright © 2011-2022 走看看