将指向 istream 和 ostream 的指针存储在类C++中

Store pointer to istream and ostream in a class C++

本文关键字:存储 C++ 指针 istream ostream      更新时间:2023-10-16

game.h

#ifndef GAME_H
#define GAME_H
#include <string>
#include <iostream>
#include "piece.h"
using namespace std;
class Game
{
    private:
        string white;
        string black;
        string title;
        istream* in;
        ostream* out;
    public:
        Game();
        Game(istream&, ostream&);
        void display(Colour, short);
};
#endif

游戏.cpp

#include <iostream>
#include <string>
#include <sstream>
#include "game.h"
#include "board.h"
#include "piece.h"
using namespace std;
Game::Game()
{
    //nothing
}
Game::Game(istream& is, ostream& os)
{
    in = is;
    out = os;
}
void Game::display(Colour colour, short moves)
{
    //out << "a";
}

我正在尝试在类的其他部分使用 istream 和 ostream,但我不能,因为 g++ 不允许我引用 in 。有什么想法吗?

你只需要一个引用变量,而不是一个指针。

class Game
{
    private:
        ...
        istream& in;
        ostream& out;
    public:
        Game(istream&, ostream&);
};
Game::Game(istream& is, ostream& os)
    : in( is ),
      out( os )
    { }

现有代码的编译是因为几个语言怪癖:

  • istream/ostream 可以void*,以允许您检查其错误状态,如

      if( in ) { do_something( in ); }
    
  • 您的编译器显然允许将void*转换为ostream*(我相信错误,您至少应该从中得到警告)。

你应该尊重指针:

*out << "a";
为了

更方便使用,为了不每次都尊重指针,并且为了提高可读性,您可以使用引用而不是指针。

class Game
{
    // ...
    std::istream& in;    // notice explicit namespace std::
    std::ostream& out;
    // ...
};

然后你可以写:

out << "a";

另外,这样做不是一个好习惯:

using namespace std;

这样,您将公开 std 命名空间的名称。

is是引用而不是指针,因此如果要存储指针,则需要使用地址运算符in = &is;

但请注意,is 在方法调用后可能立即不复存在,因此您很容易得到无效指针。确保你至少记录了这个事实。

如果存储指针,则需要取消引用它们,例如 *in*out << ...