构造函数初始化错误
Constructor initialization error
我正在创建一个简单的卡牌游戏基础,现在我正在制作创建代表每个玩家的对象的类。构造函数似乎有一个问题: 'Spelare'的构造函数必须显式初始化引用成员'leken'
class Spelare {
public:
Spelare(Kortbunt& kortlek, bool ar_dator) {leken = kortlek; dator = ar_dator;} //Constructor
int spela();
private:
Kortbunt hand; //The cards in the players hand
Kortbunt& leken; //The cards on the table
const bool dator; //Is this player a computer?
};
将构造函数更改为:
Spelare(Kortbunt& kortlek, bool ar_dator) : leken(kortlek), dator(ar_dator) {}
问题是引用一旦被声明和初始化就不能被重新赋值。构造函数试图声明但不初始化引用,然后对其进行赋值——这将失败。
你需要通过构造函数的初始化列表初始化引用。您还需要对dator
执行相同的操作,因为它是const
-但这只是一般的良好实践。
引用和const成员必须这样初始化:
Spelare(Kortbunt& kortlek, bool ar_dator) : leken(kortlek), dator(ar_dator) {}
然而,把引用作为类成员让我很痛苦,所以我建议不要这样做。
试试这个:
class Spelare {
public:
Spelare(Kortbunt& kortlek, bool ar_dator)
: leken(kortlek), dator(ar_dator)
{}
// ...
};
所以技巧是在初始化列表中初始化leken
。必须这样做,因为它是一个引用(注意其声明中的&
)。在类中声明的引用也必须这样初始化。
最后,由于dator
是const,不能赋值,因此也必须在初始化列表中初始化。
类成员的初始化是而不是在actor主体内进行的。当进入函数体时,所有的成员变量都已经初始化了,所以要执行赋值。
类成员的初始化通常使用初始化列表执行。
struct Foo {
Foo(int a, int b, int c)
: a{a}, b{b}, c{c} // Initialization list.
{
/* ctor body */
}
int a;
int b;
const int c;
std::string s{"Test"}; // C++11 also allows non-const in class initialization.
};
由于引用必须初始化,指向某些数据,并且可以不重新赋值,稍后指向其他一些数据,下面是一个错误。
struct Bar {
Bar(Foo& f) // Error: uninitialized reference member.
{
f_ = f; // If f_ had been initialized this is assignment to where f_ points,
// not reassignment of what data f_ is a reference to.
}
Foo& f_;
};
const
成员也不能赋值(自然),它们必须初始化为某个值
相关文章:
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- 分段错误 - 读取初始化指针的数组
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 修复未初始化的局部变量错误
- 初始化迭代器错误 C++ 在 GCC 编译器中
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 类型为 "Bucket&"(未限定的 const 限定)的引用不能使用 "SortedList." 类型的值进行初始化 如何修复此错误?
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么我在向量初始化时收到此错误?
- C1001内部编译器错误是由于矢量初始化(如数组)引起的
- 初始化thread_local叮当中的错误
- Eclipse:错误:初始化模式失败(无法连接到目标)
- C 错误:初始化量太多
- Seg 错误初始化列表向量与控制台输入
- 通过传递的指针段错误初始化 char 数组
- c++错误:初始化器元素不是常量
- C++错误:初始化结构实例的向量数组成员
- Visual Studio C++11g编译错误-初始化程序过多
- OpenCV 错误:初始化 OpenCLDevices 中的 GPU API 调用 (-1001)