c++ - 为什么要调用复制操作员?
问题描述
在最后一行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);
}
解决方案
在最后一行
myA = foo(myOtherB);
,函数将返回类型为 B 的对象。
不对。您的函数A
按值返回类型的对象。这意味着,您为这个对象提供的任何值都将用于构造该确切类型的新对象。换句话说:
int foo(float a) {
return a + 0.5;
}
int u;
u = foo(9.3);
// u has a value of 10
不要期望u
持有一个 int 不能的值。
如果您使用用户定义的类型,同样的事情:
A foo(A& input) {
input.foo();
return input; // this expression returns a new A
// using the value of `input`
}
A myA;
myA = foo(myOtherB);
// why would `myA` be anything else than the value of an A?
那么,这里发生了什么?
B foo() A copy ctor //what calls this? A op=
A foo(A& input) {
input.foo(); // prints B foo, virtual call. a reference to A that
// points to an object of subclass type B
return input; // copy `input` into the return value object
}
然后, operator= 被调用。
推荐阅读
- python - 无法在烧瓶中正确提供静态文件
- javascript - 如何创建编辑按钮在 CRUD 中正常工作?
- python - 是否可以将多个变量传递给未在调用它的前一个函数中本地声明的函数(或全局声明)?
- android - MVVM Android MediatorLiveData 嵌套调用
- pandas - PANDAS:一种组合按字段分组的行的方法
- sql - 使用 ON 子句连接具有相同列名的表
- python - pandas.DataFrame.groupby 省略列
- python - Pandas - 基于与另一列的交叉引用计算新值
- java - java mockito:有没有办法伪造一个不存在的类?
- java - 如何让接口扩展它自己的泛型类型