繁体   English   中英

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

[英]Store pointer to istream and ostream in a class 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

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";
}

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

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

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;使用地址运算符in = &is;

但请明白, is可以停止的方法调用后立即存在的,因此,你可以很容易地与无效指针结束。 确保您至少记录了这一事实。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM