构造函数的细节

xiaoxiao2021-02-28  121

点击(此处)折叠或打开

#include<iostream> using namespace std; class A { public:         A(){cout << "Hello world\n";} }; class B:public A { }; int main() {         A *c = new B;//这里不能写成B *c = new A;         return 0; } 运行结果: [root@bogon c++]# ./a.out Hello world 运行结果表明执行了A的构造函数 new B的执行过程:首先调用operator new 分配足够的空间,然后执行A的构造函数,B的构造函数。 #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;                         } 运行结果; [root@bogon c++]# ./a.out Hello world hi fare #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; } 运行结果: [root@bogon c++]# ./a.out Hello world hi Bye fare 由此可见析构函数应尽量声明为虚函数!构造函数不能为虚函数。无论构造函数还是析构函数尽量不要调用虚函数! 2016.9.11

点击(此处)折叠或打开

#include<iostream> using namespace std; class S { public:     S(){cout << "Hello world";fun();}     virtual void fun(){cout << "funS";}     ~S(){cout << "Bye";} }; class Derived :public S { public:     Derived(){cout << "hi";}     virtual void fun(){cout << "funDe";}     virtual ~Derived(){cout << "farewell";} }; int main() {     Derived *de = new Derived();     delete de;     return 0; } 运行结果:
[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语言指针详解-完整版... 给主人留下些什么吧!~~ 评论热议
转载请注明原文地址: https://www.6miu.com/read-56808.html

最新回复(0)