【发布时间】:2019-05-15 20:44:12
【问题描述】:
在最后一行myA = foo(myOtherB);,函数将返回类型为A的对象,因此;这就像说`myA = input,但是为什么是复制构造函数呢?
输出:
B foo()
A copy ctor //what calls this?
A op=
要调用复制构造函数,我们必须在初始化期间使用赋值运算符,例如:B newB = myOtherB;
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A ctor" << endl; }
A(const A& a) { cout << "A copy ctor" << endl; }
virtual ~A() { cout << "A dtor" << endl; }
virtual void foo() { cout << "A foo()" << endl; }
virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }
};
class B : public A {
public:
B() { cout << "B ctor" << endl; }
virtual ~B() { cout << "B dtor" << endl; }
virtual void foo() { cout << "B foo()" << endl; }
protected:
A mInstanceOfA; // don't forget about me!
};
A foo(A& input) {
input.foo();
return input;
}
int main() {
B myB;
B myOtherB;
A myA;
myOtherB = myB;
myA = foo(myOtherB);
}
【问题讨论】:
-
这段代码无法编译
-
查看
foo的返回类型。注意到有什么遗漏了吗? -
foo()返回一个A对象按值,而不是按引用,因此是@ 的复制正在返回 987654328@,并且该副本需要调用复制构造函数。