gpt4 book ai didi

c++ - 构造函数中的引用 vector : uninitialized reference

转载 作者:行者123 更新时间:2023-11-30 02:33:53 26 4
gpt4 key购买 nike

vector using namespace 的使用是错误的。可能是错字。请更改如下。使用 std::vector我必须遵循以下代码:

class MyClass{

private:

std::vector<float>& myvector;

public:

MyClass(int k,std::vector<float>& vector){

(...)

this->myvector=vector;

(...)

}

我像这样创建一个 MyClass 对象:

(...)

std::vector<float> vector;
vector.reserve(k);

(...)

MyClass A= MyClass(k,vector);

(...)

弹出一个错误告诉我 MyVector 是一个未初始化的引用。我只是想让 MyClass 将一些数据存储在 MyVector 中并返回它。我应该改用指针吗?

谢谢

最佳答案

您需要使用 constructor initializer list :

MyClass(int k, std::vector<float>& v)
: myvector(v)
{
(...)
}

也不要使用类型的名称作为变量/参数的名称。

这个很好的解释来自 user3159253

members of the class are initialized before constructor body. So if you don't initialize them explicitly, they're initialized with their respective default constructors. This is often Ok for most datatypes (although they would be initialized twice, once with default constructor and the second time in the body), but not with references which don't have default constructors at all

关于c++ - 构造函数中的引用 vector : uninitialized reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34991886/

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