【问题标题】:Class with std::istream reference initialization具有 std::istream 引用初始化的类
【发布时间】:2015-09-14 16:09:50
【问题描述】:

我在初始化这个类时遇到问题:

class Player{
  ///
  std::istream ∈
  ///
};

尝试这样:

Player::Player():in(cin){
  ///
}

谁能指出我如何做到这一点的正确方向? 另外,初始化后,我可以通过说类似的话来更改引用

stringstream ss("test");
Player p;
p.in = ss;

提前致谢

【问题讨论】:

  • 只能初始化引用,以后不能更改。您最多可以为被引用的内容分配新值,而不是引用本身。

标签: c++ class istream member-initialization


【解决方案1】:

你还没有声明构造函数,只是定义了它。
声明构造函数并将其设置为 public:

class Player{
public:
  Player(); // You need to declare the constructor
  std::istream ∈
};

Player::Player():in(cin)
{}

int main()
{
    Player p;
}

我可以更改参考吗?

不,您不能更改引用,只能更改被引用的值。

【讨论】:

  • @NicholasPaxton 您希望它公开,以便从 main 轻松访问它。
猜你喜欢
  • 2016-10-01
  • 2017-10-29
  • 2012-12-18
  • 1970-01-01
  • 2016-09-17
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多