如何在C 中超负荷运算符

How to overload ofstream operator in c++?

本文关键字:超负荷 运算符 中超      更新时间:2023-10-16

我正在尝试超载操作员,以便我可以将其写入我创建的文件中:

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)

不正确。

删除它。

另外,

  1. ofstream更改为std::ostream,因此您可以使用任何std::ostream,而不仅仅是std::ofstream
  2. 将第二个参数类型更改为 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::ostreamofstream实例。

4((可选,但良好的实践(。将operator<<()的第二个参数更改为const参考。

您的问题有些误导,因为代码示例是指未在任何地方定义的类型。将来,提供MCVE