你熟悉构造函数的调用吗?

8 篇文章 0 订阅
5 篇文章 0 订阅
#include <iostream>
using namespace std;

class Base {
	friend ostream& operator<<(ostream &os,Base &b);
public:
	Base() {
		cout << "Base()" << endl;
	}
	~Base() {
		cout << "~Base()" << endl;
	}
	Base(const Base &b) {
		cout << "Copy Base()" << endl;
	}
	Base& operator=(const Base &b) {
		cout << "Copy assignment" << endl;
		return *this;
	}
};

int main() {
	 Base b;
	 cout << "---------------" << endl;
	 Base b1 = b; //拷贝初始化,调用拷贝构造函数。(注意和下面的区别:
	 	 	 	 //现在b已经初始化了,不用再调用相应的构造函数了)
	 	 	 	 //注意:不是调用copy assignment operator
	// string s = "abc"; // ①先调用对应的构造函数构建一个临时对象temp("abc")
	 	 	 	 	 	 // ②再调用copy constructor 初始化s。

	 cout << "---------------" << endl;
	 Base b2(b); //拷贝初始化,调用拷贝构造函数
	 cout << "---------------" << endl;
	 Base b3;
	 cout << "---------------" << endl;
	 b3 = b;//调用Copy assignment
	 cout << "---------------" << endl;
 }




看看这题的输出结果:

#include <iostream>
class human {
public:
	human() {
		human_num++;
	}
	;
	static int human_num;
	~human() {
		human_num--;
		print();
	}
	void print() {
		cout << "human num is: " << human_num << endl;
	}
protected:
private:
};
int human::human_num = 0;
human f1(human x) {
	x.print();
	return x;
}
int main(int argc, char* argv[]) {
	human h1;
	h1.print();
	human h2 = f1(h1);
	h2.print();
	return 0;
}
输出:
human num is: 1
human num is: 1
human num is: 0
human num is: 0
human num is: -1
human num is: -2
----------------------------
分析:
1. human h1;  //调用构造函数,hum_num++后为1 ; h1.print();  输出:"human is 1" 。
2. human h2  = f1(h1); //在调用函数 f1(h1)的过程中,由于函数参数是按值传递对象,调用 默认的复制构造函数(实参h1的副本h1_copy给形参x) ,它并没有对hum_num++,所以hum_num 仍= 1,所以x.print()输出:"human is 1" 。
3. 由于该函数 f1 返回一个human 对象(其实返回的是副本),所以又调用默复制认构造函数,创建一个返回值的副本 h1_return。
4. 在退出函数 f1 时,要销毁实参h1传递过来的副本对象h1_copy,调用析构函数(human_num--),输出:"human is 0"。
5. 把返回值的副本赋给h2,又调用默认构造函数(  human_num = 0);   h2.print();   //输出: human is 0;
6. 在退出main()函数的时候,先销毁h2,调用析构函数(human_num--),输出"human_num is -1"。
7.  然后销毁h1,调用析构函数(human_num--),输出"human_num is -2"。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值