2011-04-03 77 views
6

game.h商店指针istream和ostream的一类C++

#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 ++不会让我参考进来。任何想法?

回答

6

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

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

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

现有的代码编译,因为一对夫妇语言怪癖:

  • istream/ostream是convrtible到void*,让你检查,如

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

+0

我还使用了http://stackoverflow.com/questions/366955/obtain-a-stdostream-either-from-stdcout-or-stdofstreamfile/366969#366969的帮助 – Steven 2011-04-04 01:29:37

2

is是参考不是指针,因此,如果要存储一个指针,你需要使用地址操作in = &is;

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

+0

了<< “一” 给我: game.cpp:在成员函数 'void游戏::显示(颜色,短整型)': game.cpp:23:错误:类型无效的操作数'std :: ostream *'和'const char [2]'为二元运算符<<' – Steven 2011-04-03 10:44:57

+0

@Steven因为'in'是一个指针。因此,如果你想使用它所指向的流,你需要使用解引用运算符'* out' – 2011-04-03 10:46:32

+0

@Let_Me_Be谢谢,但是现在它在那条线上给出了分段错误。 – Steven 2011-04-03 10:53:32

4

你应该尊重指针:

*out << "a"; 

为了更方便使用,每次不尊重的指针,更多的可读性,你可以用引用来代替指针。

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

然后,你可以写:

out << "a"; 

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

using namespace std; 

这种方式,您都暴露std名字空间的名字。

+0

@Magnus谢谢!纠正。 +1 – 2011-04-04 06:53:52

1

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