gpt4 book ai didi

c++ - 错误 : invalid initialization of reference of type 'int&' from expression of type 'const int'

转载 作者:IT老高 更新时间:2023-10-28 23:13:18 26 4
gpt4 key购买 nike

这是一个与 this question 中的代码无关的问题。 ,关于以下模板函数。

template <class T>
class Object : public Container {
public:
T& object;

Object(const T& obj) : object(obj) {}
};

这是调用构造函数的代码:

template <class T>
void Array::add_element(const T& element)
{
vec.push_back(new Object<T>(element));
}

这段代码编译得很好,但是只要我在 main 中添加一行调用它:

Array array;
int i = 3;
array.add_element(i);

我收到编译器警告:error: invalid initialization of reference of type 'int&' from expression of 'const int'.

那是关于什么的?我传入了一个 int。它不应该自动变成一个 const int& 吗?为什么编译器会提示?

最佳答案

obj是一个常量引用。 object是一个非常量引用。

您不能从 const 引用初始化非 const 引用,因为这样做会破坏首先拥有 const 引用的目的。

如果您想要 Object 的实例能够修改int传递给它的构造函数,那么构造函数应该采用非常量引用。如果你不这样做,那么数据成员应该是一个 const 引用。

无论如何,如果你使用 new,你就是在为自己埋下麻烦。分配具有引用作为数据成员的对象。确保您删除 Object您的问题之前 i超出范围(或者无论如何,确保 Objectobject 超出范围后不使用其成员 i

关于c++ - 错误 : invalid initialization of reference of type 'int&' from expression of type 'const int' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11371216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com