如何在C 中超负荷运算符
How to overload ofstream operator in c++?
我正在尝试超载操作员,以便我可以将其写入我创建的文件中:
typedef struct Square {
pawn *pawns[2] = { nullptr,nullptr };
}square;
class game {
player players[2];
score score1 = 0, score2 = 0;
square board[10][10];
public:
//constructor
friend class ofstream& operator<< (ofstream& out, game curr)
{
for (int i = 0; i <= 20; i++)
{
out << "=";
}
for (int index = 0; index < 10; index++)
{
out << 'n';
for (int j = 0; j <= 10; j++)
{
out << "| ";
}
out << index << 'n';
for (int i = 0; i <= 20; i++)
{
out << "=";
}
}
out << 'n';
for (int index = 0; index < 10; index++)
{
out << " " << index;
}
return(out);
}
我主要获得错误C2676:
严重性代码描述项目文件错误C2676二进制'&lt;&lt;':'ofStream'并未定义此操作员或转换为可接受的操作员可接受的类型
我在做什么错?
行中的单词 class
friend class ofstream& operator<< (ofstream& out, game curr)
不正确。
删除它。
另外,
- 将
ofstream
更改为std::ostream
,因此您可以使用任何std::ostream
,而不仅仅是std::ofstream
。 - 将第二个参数类型更改为
const&
。
friend std::ostream& operator<< (std::ostream& out, game const& curr)
{
...
}
最好将功能的实现从类定义中移出。它将允许您在.cpp文件中实现。
为此,我建议:
// Declare the class
class game;
// Declare the funtion
std::ostream& operator<< (std::ostream& out, game const& curr);
// Make the function a friend of the class.
class game
{
...
friend std::ostream& operator<< (std::ostream& out, game const& curr);
};
// Define the function outside the class definition.
std::ostream& operator<< (std::ostream& out, game const& curr)
{
...
}
1(从线路friend class ofstream& operator<< (ofstream& out, game curr)
删除class
。
2(在此声明上方的某个位置添加#include <iostream>
。
3(删除using namespace std
(由于您的代码是类定义,如果要在多个源文件中使用类类型,通常在标题文件中属于标题文件,而using namespace std
在标题文件中是不好的练习(并替换所有用std::ostream
的ofstream
实例。
4((可选,但良好的实践(。将operator<<()
的第二个参数更改为const
参考。
您的问题有些误导,因为代码示例是指未在任何地方定义的类型。将来,提供MCVE
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 我可以超负荷运算符,以指针和非构造模板对象
- 如何在C 中超负荷运算符
- C 超负荷取消运算符