c++中继承中的构造函数初始化问题_形参列表方法1

#include
#include
using namespace std;
class Parent
{
public:
	Parent(string name, char sex, int age);//构造函数
	void printParent();
protected:
	string name;
	char sex;
	int age;
};
Parent::Parent(string name, char sex, int age)
{
	this->name = name;
	this->sex = sex;
	this->age = age;
}
void Parent::printParent()
{
	cout << "name:" << name << endl;
	cout << "sex:" << sex << endl;
	cout << "age:" << age << endl;
}


class Son :public Parent
{
public:
	Son(string name, char sex, int age, int height, int tall) :Parent(name, sex, age)
	{
		this->height = height;
		this->tall = tall;
	}
	void printSon()
	{
		cout << "name:" << name << endl;
		cout << "sex:" << sex << endl;
		cout << "age:" << age << endl;

		cout << "height:" << height << endl;
		cout << "tall:" << tall << endl;
	}
private:
	int height;
	int tall;
};



int main(void)
{
	Parent p1("jack", 'm', 20);
	p1.printParent();
	cout << "-----------------------" << endl;
	Son s1("mark", 'm', 2, 32, 42);
	s1.printSon();
	//s1.printParent();//子类可以调用父类的方法,子类就是特殊的父类

	system("pause");
	return 0;
}

/*
派生类的构造函数受继承关系的影响,每个派生类构造函数除了初始化自己的数据成员之外,还要初始化基类。
派生类的合成默认构造函数:除了初始化派生类的数据成员之外,它还初始化派生类对象的基类部分。基类部分
由基类的默认构造函数初始化:
*/

 

你可能感兴趣的:(c++)