初始化列表的使用场景三四:在子类构造函数的初始化列表中给父类有参构造函数初始化

Father.h------------------
#pragma once
#include <iostream>
using namespace std;

class CFather
{
public:
	CFather(string strXing,string strProvince,int iAge);
	virtual ~CFather();

	string GetXing();
	string GetProvince();
	int GetAge();

private:
	string m_strXing;
	string m_strProvince;
	int m_iAge;
};




Father.CPP---------------
#include "Father.h"




CFather::CFather(string strXing, string strProvince, int iAge)
{
	this->m_strXing = strXing;
	this->m_strProvince = strProvince;
	this->m_iAge = iAge;
}

CFather::~CFather()
{
}

std::string CFather::GetXing()
{
	return m_strXing;
}

std::string CFather::GetProvince()
{
	return m_strProvince;
}

int CFather::GetAge()
{
	return m_iAge;
}

Son.h---------------------
#pragma once

#include <iostream>
using namespace std;
#include "Father.h"

class CSon :
	public CFather
{
public:
	CSon(string strXingTmp, string strProTmp, int iAgeTmp,string SonName);
	virtual ~CSon();

	string m_strSonName;
	string GetSonName();
};


Son.cpp---------------------
#include "Son.h"


CSon::CSon(string strXingTmp, string strProTmp, int iAgeTmp, string SonName) :
CFather(strXingTmp, strProTmp, iAgeTmp)  //通过子类构造函数给父类构造函数传递参数同时也传递给        
                                         //子类自己其他成员初始值
{
	this->m_strSonName = SonName;
}


CSon::~CSon()
{
}

std::string CSon::GetSonName()
{
	return this->m_strSonName;
}

main.cpp--------------------

#include "Son.h"
#include <iostream>
#include <string>
using namespace std;


void test()
{
	CSon son("李", "江苏", 40, "lele");
	cout << "sonname:" << son.GetSonName() <<"姓:"<<son.GetXing()<<"省份:"<<son.GetProvince()<<"父亲年龄:"<<son.GetAge()<< endl;

}


int main()
{
	test();


system("pause");
return EXIT_SUCCESS;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值