2
我有一个关于拷贝构造函数问题,假设一个class A
包含一个int
,使用默认构造函数,拷贝构造函数(?),和构造函数接收int
为什么复制构造函数需要是const?
class A {
int value;
public:
A(): value(0) {} // Default
A(A& copy): value(copy.value) {} // Copy (?)
A(const int n): value(n) {} // Receives an int for 'value'
int get_value() { return value; } // Return value
};
和包含一个A pointer
类,命名BoxForA
:
class BoxForA {
A *obj;
public:
BoxForA(): obj(nullptr) {}
BoxForA(const int a) { obj = new A(a); }
A popf(){ return *obj; } // Returns the content of obj_A (an A element)
};
和主(将打印方式中三3
):
int main() {
A a(3);
A b = a; // Calling copy constructor for b (this works with non-const parameter)
BoxForA box1(3);
A c = box1.popf(); // Calling copy constructor for c (this doesn't work with non-const parameter)
cout << "a = " << a.get_value() << endl;
cout << "b = " << b.get_value() << endl;
cout << "c = " << c.get_value() << endl;
return 0;
}
当我编译,编译器给了我这个错误:
error: invalid initialization of non-const reference of type ‘A&’ from an rvalue of type ‘A’
A c = box1.popf();
^
只是,我想我的拷贝构造函数需要const的参数,而不是非const,所以编辑我的拷贝构造函数这样:
A(const A& obj): value(obj.value) {}
我的程序现在编译没有错误,显示此输出:
a = 3
b = 3
c = 3
不错!我找到了解决方案:D ....没有,因为我不知道它为什么起作用。
你能告诉我为什么会发生这种情况吗?为什么复制构造函数似乎有const
参数?
'box1.popf()'返回一个临时的:
,如果你写你得到完全相同的问题。 –
如果你说,它必须是恒定的,否。如果你问是否应该,那么是的。 'cpy ctor'引用同一类的一个对象,并将它的值复制到正在创建的新对象上,只要它不改变'rhs'的值,我们就可以将它传递给它const引用 – Raindrop7