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

//继承
//代码的重用性
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");
}
*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值