简体   繁体   English

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

[英]Store pointer to istream and ostream in a class C++

game.h 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 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";
}

I'm trying to use the istream and ostream in other parts of my class but I can't because g++ won't let me reference is to in. Any ideas? 我正在尝试在我班级的其他部分使用istream和ostream,但我不能,因为g ++不会让我参考进来。任何想法?

You simply want a reference variable, not a pointer. 您只需要一个引用变量,而不是指针。

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

Game::Game(istream& is, ostream& os)
    : in( is ),
      out( os )
    { }

The existing code compiles because of a couple language quirks: 由于一些语言怪癖,现有代码编译:

  • istream / ostream are convrtible to void* to allow you to check their error status as in istream / ostream可以void*以允许您检查其错误状态

      if( in ) { do_something( in ); } 
  • your compiler apparently allowed void* to be converted to ostream* (I believe in error, and you should at least get a warning from this). 你的编译器显然允许将void*转换为ostream* (我相信错误,你应该至少得到一个警告)。

You should deference the pointer: 你应该遵循指针:

*out << "a";

For more convenient use, to not deference the pointers each time, and for more readability you can use references instead of pointers. 为了更方便的使用,每次都不要遵循指针,为了更好的可读性,你可以使用引用而不是指针。

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

Then you can write: 然后你可以写:

out << "a";

Plus, it is not a good habit to do so: 另外,这样做不是一个好习惯:

using namespace std;

This way you are exposing the names of std namespace. 这样您就可以公开std命名空间的名称。

is is a reference not a pointer, therefore if you want to store a pointer you need to use the address operator in = &is; is是引用而不是指针,因此如果要存储指针,则需要in = &is;使用地址运算符in = &is;

But please realize that is can cease to exist immediately after the method call, therefore you can easily end up with an invalid pointer. 但请明白, is可以停止的方法调用后立即存在的,因此,你可以很容易地与无效指针结束。 Make sure that you at least document this fact. 确保您至少记录了这一事实。

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

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

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