欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

继承和构造函数析构函数调用顺序

程序员文章站 2022-05-14 09:06:03
...
//继承
//代码的重用性
using namespace std;

/*
//人类
class Human{
public:
	void say(){
		cout << "说话" << endl;
	}
protected:
	char* name;
	int age;
};

//男人
class Man : public Human{
public:
	//泡妞
	void chasing(){
		cout << "泡妞" << endl;		
	}
private:
	//兄弟
	char* brother;
};

void work(Human& h){
	h.say();
}

void main(){
	Man m1;
	m1.say();

	//1.父类类型的引用或指针
	Human* h_p = &m1;
	h_p->say();

	Human &h1 = m1;
	h1.say();

	//子类对象初始化父类类型的对象
	Human h2 = m1;

	system("pause");
}
*/

//向父类构造方法传参
//人类
/*
class Human{
public:
	Human(char* name, int age){
		this->name = name;
		this->age = age;
	}
	void say(){
		cout << "说话" << endl;
	}
protected:
	char* name;
	int age;
};

//男人
class Man : public Human{
public:
	//给父类构造函数传参,同时给属性对象赋值
	Man(char *brother, char *s_name, int s_age, char *h_name, int h_age) : Human(s_name, s_age), h(h_name,h_age){
		this->brother = brother;
	}
	//泡妞
	void chasing(){
		cout << "泡妞" << endl;
	}
private:
	//兄弟
	char* brother;
	Human h;
};

void main(){
	Man m1("danny","jack",18,"jason",18);

	system("pause");
}
*/


//构造函数与析构函数调用的顺序
/*
class Human{
public:
	Human(char* name, int age){
		this->name = name;
		this->age = age;
		cout << "Human 构造函数" << endl;
	}
	~Human(){
		cout << "Human 析构函数" << endl;
	}
	void say(){
		cout << "说话" << endl;
	}
protected:
	char* name;
	int age;
};

//男人
class Man : public Human{
public:
	//给父类构造函数传参,同时给属性对象赋值
	Man(char *brother, char *s_name,int s_age) : Human(s_name, s_age){
		this->brother = brother;
		cout << "Man 构造函数" << endl;
	}
	~Man(){
		cout << "Man 析构函数" << endl;
	}
	//泡妞
	void chasing(){
		cout << "泡妞" << endl;
	}
private:
	//兄弟
	char* brother;	
};

void func(){
	//父类构造函数先调用
	//子类的析构函数先调用
	Man m1("danny", "jack", 18);
}

void main(){
	func();

	system("pause");
}
*/


//子类对象调用父类的成员
/*
class Human{
public:
	Human(char* name, int age){
		this->name = name;
		this->age = age;
		cout << "Human 构造函数" << endl;
	}
	~Human(){
		cout << "Human 析构函数" << endl;
	}
	void say(){
		cout << "说话" << endl;
	}
public:
	char* name;
	int age;
};

//男人
class Man : public Human{
public:
	//给父类构造函数传参,同时给属性对象赋值
	Man(char *brother, char *s_name, int s_age) : Human(s_name, s_age){
		this->brother = brother;
		cout << "Man 构造函数" << endl;
	}
	~Man(){
		cout << "Man 析构函数" << endl;
	}
	//泡妞
	void chasing(){
		cout << "泡妞" << endl;
	}
	void say(){
		cout << "男人喜欢装逼" << endl;
	}
private:
	//兄弟
	char* brother;
};

void main(){
	//是覆盖,并非动态
	Man m1("alan","john",18);
	m1.say();
	m1.Human::say();

	m1.Human::age = 10;

	system("pause");
}
*/