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

Ste*_*ven 6 c++

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
Run Code Online (Sandbox Code Playgroud)

game.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";
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试在我班级的其他部分使用istream和ostream,但我不能,因为g ++不会让我参考进来.任何想法?

Pot*_*ter 6

您只需要一个引用变量,而不是指针.

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

Game::Game(istream& is, ostream& os)
    : in( is ),
      out( os )
    { }
Run Code Online (Sandbox Code Playgroud)

由于一些语言怪癖,现有代码编译:

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

      if( in ) { do_something( in ); }
    
    Run Code Online (Sandbox Code Playgroud)
  • 你的编译器显然允许void*转换为ostream*(我相信错误,你应该至少得到一个警告).