在继承类中,父类在子类中初始化问题,已解决

#include<iostream>

using namespace std;

//继承与组合混搭情况下,构造和析构调用原则
class Grandfather
{
public:
	Grandfather( char * g)
	{
		this->G_t1=g;
		cout<<"G_t1====== "<<G_t1;
		cout<<"我是顶头的爷爷的构造函数\n";
	}

	~Grandfather()
	{
		cout<<"我是顶头的爷爷的析构函数\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<<"这是父亲的构造函数\n";
	}
	~Father()
	{
		cout<<"这是父亲的析构函数 \n";
	}
protected:
	char *F_t1;
private:
};
class Child:public Father
{
public:
	Child():Father("dsa"),g1("sfsdfds"),g2("g2")//不懂
	{

		cout<<"这是孩子的构造函数 \n";
	}
	~Child()
	{
		cout<<"这是孩子的析构函数 \n";
	}
protected:
	int C_t1;
	Grandfather g1;//这里这两句有疑问,为什么Grandfather明明必须有形参,但是为什么这里初始化参数反而不对了呢?
	Grandfather g2;
private:
};

void objplay()
{
	Child c1;
}
int main()
{
	
	objplay();
	system("pause");
	return 0;		
}

  不明白的是这两句

 但是这好像是套路,必须这么做呢

就像例如:

#include<iostream>

using namespace std;

//继承与组合混搭情况下,构造和析构调用原则
class Grandfather
{
public:
	Grandfather( char * g)
	{
		this->G_t1=g;
		cout<<"G_t1====== "<<G_t1;
		cout<<"我是顶头的爷爷的构造函数\n";
	}

	~Grandfather()
	{
		cout<<"我是顶头的爷爷的析构函数\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<<"这是父亲的构造函数\n";
	}
	~Father()
	{
		cout<<"这是父亲的析构函数 \n";
	}
protected:
	char *F_t1;
private:
};
class Child:public Father
{
public:
	Child():Father("dsa"),g1("sfsdfds"),g2("g2"),f1("f1")//不懂
	{

		cout<<"这是孩子的构造函数 \n";
	}
	~Child()
	{
		cout<<"这是孩子的析构函数 \n";
	}
protected:
	int C_t1;
	Father f1;
	Grandfather g1;//这里这两句有疑问,为什么Grandfather明明必须有形参,但是为什么这里初始化参数反而不对了呢?
	Grandfather g2;
private:
};

void objplay()
{
	Child c1;
}
int main()
{
	
	objplay();
	system("pause");
	return 0;		
}

  运行结果是:

 

发现一个真理没?只要调用一个Father就必须调用一个爷爷啊

套路

转载于:https://www.cnblogs.com/xiaochige/p/6613022.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值