C++中对象初始化赋值是否需要调用operator=函数

一般对于初始化类变量有两种方式:

A a;

A b = a;

另一种方式是:

A a ;

A b;

a =b;

对于第一种方式,编译器相当于在b的初始化的时候,用a的引用作为复制构造函数的参数进行操作,相当于A b(a);

而对于第二种方式,则应该是用了赋值构造函数,也就是=的重载。因为a和b本身都已经重载了,就相当于把b的值赋给a了。

比如代码如下:

class mytest{

public:
	int a;
	mytest(int s) :a(s){};//构造函数

	mytest(const mytest & test){//复制构造函数
		a = test.a;
		cout << "copy constructor used!" << endl;
	}
	void operator = (const mytest & test){//赋值构造函数
		a = test.a;
		cout << "copy assignment used!" << endl;
		//return *this;
	}
};

int main(){

	mytest test1(2);
	mytest test2 = test1;

	cout << "---------------" << endl;

	mytest test3(2);
	test3 = test1;

	cout << "---------------" << endl;

	
	cout << "value of a in test2 is: " << test2.a << endl;
	cout << "value of a in test3 is: " << test3.a << endl;

	system("pause");
	return 0;
}

它的输出是:

需要注意的是,如果我把赋值构造函数的返回值设定为A类对象,由复制构造函数的用法,则赋值构造函数里面还会再次调用复制构造函数,比如:

class mytest{

public:
	int a;
	mytest(int s) :a(s){};//构造函数

	mytest(const mytest & test){//复制构造函数
		a = test.a;
		cout << "copy constructor used!" << endl;
	}
	mytest operator = (const mytest & test){//赋值构造函数
		a = test.a;
		cout << "copy assignment used!" << endl;
		return *this;
	}
};

int main(){

	mytest test1(2);
	mytest test2 = test1;

	cout << "---------------" << endl;

	mytest test3(2);
	test3 = test1;

	cout << "---------------" << endl;

	
	cout << "value of a in test2 is: " << test2.a << endl;
	cout << "value of a in test3 is: " << test3.a << endl;

	system("pause");
	return 0;
}

它的结果就是:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值