当函数在传递参数为对象与返回类型为对象时,它们分别调用的复制构造函数还是赋值运算符函数?
以下面一段代码讨论c++中传递的对象是赋值还是复制问题(debug)
#include<stdio.h>
#include<iostream>
using namespace std;
class A {
private:
int x, y;
public:
A() :x(0), y(0) {}
A(int x, int y) {
this->x = x;
this->y = y;
}
A(const A& a) {
x = a.x;
y = a.y;
cout << "\tcopy constructor" << endl;
}
A& operator=(const A& a) {
cout << "\toperator= is invoked" << endl;
x = a.x;
y = a.y;
return *this;
}
};
A func1(A a)
{
return a;
}
A& func2(A& a)
{
return a;
}
int main() {
std::cout << "Hello, World!" << std::endl;
A a, b, c;
cout << "func1(a) " << endl;
func1(a);
cout << "b = func1(a)" << endl;
b = func1(a);
cout << "func2(a) " << endl;
func2(a);
cout << "c=func2(a) " << endl;
c = func2(a);
cout << "end" << endl;
return 0;
}
对于传递的数据是对象时,C++调用的是复制函数,而在使用“=”的对象复制时自然是重载了"operator ="。并且重载一般是对象的引用,所以在“A& operator=(const A& a) {}”中不涉及传值,同时“return”返回的也是对象的引用也不会调用复制构造函数,大大减少了函数的调用,当然既然是赋值就应该加上一个“const”,防止对象被篡改。