【问题标题】:Constructor initialization error构造函数初始化错误
【发布时间】:2014-03-10 13:38:53
【问题描述】:

我正在创建一个简单的纸牌游戏基础,现在我正在研究创建代表每个玩家的对象的类。不过,构造函数似乎有问题:“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?
};

【问题讨论】:

  • 分配未初始化。你分配给leken,你没有初始化它,你确实需要初始化它,就像错误消息说的那样。
  • 由于悬空引用,将Kortbunt& leken 作为成员数据是非常危险的。

标签: c++ constructor reference initialization


【解决方案1】:

将您的构造函数更改为:

Spelare(Kortbunt& kortlek, bool ar_dator) : leken(kortlek), dator(ar_dator) {} 

问题是引用一旦被声明和初始化就不能被重新分配。您的构造函数尝试声明但不初始化引用,然后分配给它 - 失败。

您需要通过构造函数的初始化列表来初始化引用。您还需要对dator 执行相同的操作,因为它是const - 但一般来说这只是一个好习惯。

【讨论】:

    【解决方案2】:

    引用和常量成员必须像这样初始化:

    Spelare(Kortbunt& kortlek, bool ar_dator) : leken(kortlek), dator(ar_dator) {} 
    

    但是,作为班级成员,被推荐给我烧了几次,所以我建议不要这样做。

    【讨论】:

    • 这仍然无法编译。 dator 不能分配给任何一个。
    • 由于dator是const,所以也需要初始化不赋值。 Spelare(Kortbunt& kortlek, bool ar_dator) : leken(kortlek), dator(ar_dator) {}
    • 其实像这样 Spelare(Kortbunt& kortlek, bool ar_dator) : leken(kortlek), dator(ar_dator){};但是谢谢
    【解决方案3】:

    试试这个:

    class Spelare {
    public:
        Spelare(Kortbunt& kortlek, bool ar_dator)
            : leken(kortlek), dator(ar_dator)
        {}
    
        // ...
    };
    

    所以诀窍是在初始化列表中初始化leken。必须这样做,因为它是一个引用(注意其声明中的&)。并且类中声明的引用必须以这种方式初始化。

    最后,由于dator 是一个常量并且不能被赋值,所以它也必须在初始化列表中进行初始化。

    【讨论】:

      【解决方案4】:

      类成员的初始化在ctor体内执行。进入ctor body的时候,所有的成员变量都已经被初始化过了,所以赋值反而被执行了。

      类成员的初始化通常使用初始化列表来执行。

      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 成员不能被分配(自然),它们必须被初始化到某个值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-02
        • 1970-01-01
        • 2015-08-08
        • 2020-10-28
        相关资源
        最近更新 更多