必须初始化字段值

Field value must be initialised

本文关键字:字段 初始化      更新时间:2023-10-16

考虑我的类定义,它是一个嵌套的Ring<T>类:

template<class T>
class Ring<T>::Iterator{
private:
    int i_pos;
    Ring<T> &value;
public:
    Iterator(int index, Ring<T> &other) :  i_pos(index){
        value = other;
    }
};

构造函数引发错误,value必须初始化。所以我的猜测是,由于Iterator在类Ring内部,我们必须首先初始化Ring<T>对象,然后再构造其内部类Iterator,对吗?

Iterator(int index, Ring<T> &other) : value(other), i_pos(index){
    }

初始化变量和只分配给变量之间有很大的区别。

你在做什么

Iterator(int index, Ring<T> &other) : value(other), i_pos(index){
}

正在初始化变量 valuei_pos

当你这样做时

Iterator(int index, Ring<T> &other) :  i_pos(index){
    value = other;
}

您初始化i_pos但尝试将变量分配给构造函数体内的变量value(一旦完成所有构造和初始化,就会调用该变量(。

您应该知道,您无法分配给引用。必须初始化引用。这是因为对(初始化的(引用的任何访问都会对引用的数据(引用变量引用的数据(执行操作。

若要详细说明,请参阅以下示例代码:

int a, b = 5;
int& r = a;  // Make r reference a
r = b;  // Assign the value of b to the variable a, equal to a = b