在继承类中,父类在子类中初始化问题,已解决
生活随笔
收集整理的這篇文章主要介紹了
在继承类中,父类在子类中初始化问题,已解决
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#include<iostream>using namespace std;//繼承與組合混搭情況下,構(gòu)造和析構(gòu)調(diào)用原則
class Grandfather
{
public:Grandfather( char * g){this->G_t1=g;cout<<"G_t1====== "<<G_t1;cout<<"我是頂頭的爺爺?shù)臉?gòu)造函數(shù)\n";}~Grandfather(){cout<<"我是頂頭的爺爺?shù)奈鰳?gòu)函數(shù)\n";}
protected:char *G_t1;
private:
};
class Father:public Grandfather
{
public:Father( char *f):Grandfather("hahahah"){F_t1=f;cout<<"F_t1====== "<<F_t1;cout<<"這是父親的構(gòu)造函數(shù)\n";}~Father(){cout<<"這是父親的析構(gòu)函數(shù) \n";}
protected:char *F_t1;
private:
};
class Child:public Father
{
public:Child():Father("dsa"),g1("sfsdfds"),g2("g2")//不懂{cout<<"這是孩子的構(gòu)造函數(shù) \n";}~Child(){cout<<"這是孩子的析構(gòu)函數(shù) \n";}
protected:int C_t1;Grandfather g1;//這里這兩句有疑問(wèn),為什么Grandfather明明必須有形參,但是為什么這里初始化參數(shù)反而不對(duì)了呢?Grandfather g2;
private:
};void objplay()
{Child c1;
}
int main()
{objplay();system("pause");return 0;
}
不明白的是這兩句
?但是這好像是套路,必須這么做呢
就像例如:
#include<iostream>using namespace std;//繼承與組合混搭情況下,構(gòu)造和析構(gòu)調(diào)用原則 class Grandfather { public:Grandfather( char * g){this->G_t1=g;cout<<"G_t1====== "<<G_t1;cout<<"我是頂頭的爺爺?shù)臉?gòu)造函數(shù)\n";}~Grandfather(){cout<<"我是頂頭的爺爺?shù)奈鰳?gòu)函數(shù)\n";} protected:char *G_t1; private: }; class Father:public Grandfather { public:Father( char *f):Grandfather("hahahah"){F_t1=f;cout<<"F_t1====== "<<F_t1;cout<<"這是父親的構(gòu)造函數(shù)\n";}~Father(){cout<<"這是父親的析構(gòu)函數(shù) \n";} protected:char *F_t1; private: }; class Child:public Father { public:Child():Father("dsa"),g1("sfsdfds"),g2("g2"),f1("f1")//不懂{cout<<"這是孩子的構(gòu)造函數(shù) \n";}~Child(){cout<<"這是孩子的析構(gòu)函數(shù) \n";} protected:int C_t1;Father f1;Grandfather g1;//這里這兩句有疑問(wèn),為什么Grandfather明明必須有形參,但是為什么這里初始化參數(shù)反而不對(duì)了呢?Grandfather g2; private: };void objplay() {Child c1; } int main() {objplay();system("pause");return 0; }運(yùn)行結(jié)果是:
?
發(fā)現(xiàn)一個(gè)真理沒(méi)?只要調(diào)用一個(gè)Father就必須調(diào)用一個(gè)爺爺啊
套路
轉(zhuǎn)載于:https://www.cnblogs.com/xiaochige/p/6613022.html
總結(jié)
以上是生活随笔為你收集整理的在继承类中,父类在子类中初始化问题,已解决的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: js---BOW---页面打开方式,跳转
- 下一篇: 使用JSON JavaScriptSer