必须初始化字段值
Field value must be initialised
考虑我的类定义,它是一个嵌套的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){
}
正在初始化变量 value
并i_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
相关文章:
- 聚合初始化和删除的复制构造函数,也称为不可复制的 obejcts 作为字段
- 类内非静态字段初始化 + 对象池 - >降低可维护性/可读性
- 为什么 MSVC 和 GCC 不能使用具有默认值的字段初始化结构
- 隐式字段初始化的规则
- 在 Qt 创建器中禁用 -wmissing 字段初始值设定项警告
- 初始化构造函数中的字段-初始化器列表与构造函数正文
- C++中模板类中的静态字段初始化
- 构造函数中的字段初始化会损坏内存
- 如何从字符串字面值初始化无符号字符数组
- c++ 11统一初始化:字段初始化不是常量
- 非阻塞TCP套接字在初始化时挂起(c++)
- 在c++中使用浮点字面值初始化整型数组的成员
- 用字符串字面值初始化char *类成员
- Int数组给出疯狂的值,除非所有字段初始化为0,为什么?
- 从字符串字面值初始化字符数组是否属于数组复制初始化的情况?
- 关于 VC++ 和 Sun Studio 中的字段初始化顺序、签名比较和未使用的变量的警告
- 结构可以在方法主体中声明,但前提是它不包含成员字段初始值设定项。编译器错误与否?
- 如何在构造函数中禁用字段初始化
- 通过设置为字符串字面值初始化的c++大小的char数组会导致数组边界溢出
- 空的大括号init列表会发出关于缺少字段初始值设定项的警告