构造函数的细节

来源:互联网 发布:故宫 书目 知乎 编辑:程序博客网 时间:2024/05/18 03:50

点击(此处)折叠或打开

  1. #include<iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6.         A(){cout << "Hello world\n";}

  7. };
  8. class B:public A
  9. {

  10. };
  11. int main()
  12. {
  13.         A *c = new B;//这里不能写成B *c = new A;
  14.         return 0;
  15. }
  16. 运行结果:
  17. [root@bogon c++]# ./a.out
    Hello world
  18. 运行结果表明执行了A的构造函数
  19. new B的执行过程:首先调用operator new 分配足够的空间,然后执行A的构造函数,B的构造函数。


  20. #include
    using namespace std;
    class A
    {
    public:
            A(){cout << "Hello world\n";}
            ~A() {cout << "fare\n"; }
    };
    class B:public A
    {
    public:
            B() {cout << "hi\n";}
            ~B() {cout << "Bye\n";}
    };
    int main()
    {
            A *c = new B;
            delete c;
            return 0;
                           
    }
  21. 运行结果;
  22. [root@bogon c++]# ./a.out
    Hello world
    hi
    fare
  23. #include
    using namespace std;
    class A
    {
    public:
            A(){cout << "Hello world\n";}
             virtual ~A() {cout << "fare\n"; }
    };
    class B:public A
    {
    public:
            B() {cout << "hi\n";}
            ~B() {cout << "Bye\n";}
    };
    int main()
    {
            A *c = new B;
            delete c;
            return 0;
    }
  24. 运行结果:
  25. [root@bogon c++]# ./a.out
    Hello world
    hi
    Bye
    fare
  26. 由此可见析构函数应尽量声明为虚函数!构造函数不能为虚函数。无论构造函数还是析构函数尽量不要调用虚函数!

    2016.9.11

    点击(此处)折叠或打开

    1. #include<iostream>
    2. using namespace std;
    3. class S
    4. {
    5. public:
    6.     S(){cout << "Hello world";fun();}
    7.     virtual void fun(){cout << "funS";}
    8.     ~S(){cout << "Bye";}
    9. };
    10. class Derived :public S
    11. {
    12. public:
    13.     Derived(){cout << "hi";}
    14.     virtual void fun(){cout << "funDe";}
    15.     virtual ~Derived(){cout << "farewell";}
    16. };
    17. int main()
    18. {
    19.     Derived *de = new Derived();
    20.     delete de;
    21.     return 0;
    22. }
    运行结果:
  27. [root@bogon ~]# ./a.out
    Hello worldfunShifarewellBye[root@bogon ~]#
                                                    



<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(96) | 评论(0) | 转发(0) |
1

上一篇: 排序算法稳定性

下一篇:xdm配置

相关热门文章
  • test123
  • 编写安全代码——小心有符号数...
  • 使用openssl api进行加密解密...
  • 一段自己打印自己的c程序...
  • 彻底搞定C语言指针详解-完整版...
给主人留下些什么吧!~~
原创粉丝点击