将指向 istream 和 ostream 的指针存储在类C++中
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
游戏.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++ 不允许我引用 in 。有什么想法吗?
你只需要一个引用变量,而不是一个指针。
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;
但请注意,is
在方法调用后可能立即不复存在,因此您很容易得到无效指针。确保你至少记录了这个事实。
如果存储指针,则需要取消引用它们,例如 *in
或 *out << ...
。
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 添加存储在向量中的大整数的函数出现问题
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在std::vector上存储带有模板的类实例
- 谷歌测试中的期望值存储在哪里
- 为什么C中的通用链表中存储的数据已损坏
- 在c++中获取两个大int,并将它们存储在数组中
- 在reactor中存储eventHandlers的最佳方式是什么