【问题标题】:Store pointer to istream and ostream in a class C++在 C++ 类中存储指向 istream 和 ostream 的指针
【发布时间】:2011-07-28 14:17:24
【问题描述】:

游戏.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++ 不允许我引用 is to in。有什么想法吗?

【问题讨论】:

    标签: c++


    【解决方案1】:

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

    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*(我相信错误,您至少应该从中得到警告)。

    【讨论】:

    【解决方案2】:

    你应该尊重指针:

    *out << "a";
    

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

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

    然后你可以写:

    out << "a";
    

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

    using namespace std;
    

    这样你就暴露了 std 命名空间的名称。

    【讨论】:

    • @Magnus 谢谢!已更正。 +1
    【解决方案3】:

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

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

    【讨论】:

    • out
    • @Steven 因为in 是一个指针。因此如果你想使用它指向的流,你需要使用解引用操作符*out
    • @Let_Me_Be 谢谢,但现在它在该行给出了分段错误。
    • 我目前正在使用 cout 作为 ostream 顺便说一句
    • 啊,我看到一旦该方法调用完成就不再存在了,有什么办法吗?
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 1970-01-01
      • 2011-08-31
      • 2021-08-14
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多