C++ 不能在构造函数中调用构造函数
生活随笔
收集整理的這篇文章主要介紹了
C++ 不能在构造函数中调用构造函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#include <iostream>
using namespace std;class MyTest{public:MyTest() {}MyTest(int a, int b, int c){ //有參 構(gòu)造函數(shù)_a = a;_b = b;_c = c;}// 構(gòu)造中調(diào)?構(gòu)造是危險(xiǎn)的?為MyTest(int a, int b){ //有參數(shù)的構(gòu)造函數(shù),兩個(gè)參數(shù)_a = a;_b = b;//構(gòu)造函數(shù)中,無法嵌套構(gòu)造函數(shù) 來通過構(gòu)造函數(shù)給自己的成員變量賦值,//此構(gòu)造函數(shù)已經(jīng)又創(chuàng)建了另一個(gè)對(duì)象。MyTest(a, b, 100); //產(chǎn)生新的匿名對(duì)象//新的匿名對(duì)象 a->1 b->2 c ->100}~MyTest(){printf("MyTest~:%d, %d, %d\n", _a, _b, _c);}int getC(){return _c;}void setC(int val){_c = val;}private:int _a;int _b;int _c;
};int main(){MyTest t1(1, 2); //t1.a -->1 t1.b -->2 t1.c--->? cout << "c:" << t1.getC() << endl;
}
注:c最后的輸出結(jié)果為亂碼,構(gòu)造函數(shù)中,無法嵌套構(gòu)造函數(shù) 來通過構(gòu)造函數(shù)給自己的成員變量賦值
總結(jié)
以上是生活随笔為你收集整理的C++ 不能在构造函数中调用构造函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ 构造函数的初始化列表
- 下一篇: C++ 对象动态建⽴和释放 new 和