矛盾的错误消息 - 运算符重载<<

Contradictory Error Messages - Operator Overloading <<

本文关键字:lt 重载 运算符 错误 消息 矛盾      更新时间:2023-10-16

>问题

根据我在类中编写函数的方式,当尝试以类的朋友身份重载 << 运算符时,我会收到 2 条错误消息之一。错误消息如下所示:

// With two arguments
(engine.cpp) error: 'std::ostream& game::GameEngine::operator<<( std::ostream&, const Engine& )' must take exactly one argument.

否则,如果我尝试编译器所说的内容,我会得到这个:

// With 1 argument
(engine.h) error: 'std::ostream& game::operator<<( std::ostream& )' must take exactly two arguments.
(engine.cpp) error: no 'std::ostream& game::GameEngine::operator<<( std::ostream& )' member function declared in class 'game::GameEngine'

我认为有两个参数的参数是正确的,但我不明白为什么我会收到相互矛盾的错误消息。我正在使用'-Wall,-Wextra,-pedantic-error,-std=c++11'和其他几个警告标志来编译文件。

法典

引擎.h 来源:

#include <iostream>
namespace game {
    // Note that all variables and functions except the operator overload are static.
    class GameEngine {
    public:
      /* ... */
      friend std::ostream& operator<<( std::ostream& o, const GameEngine& engine );
    private:
      /* ... */
    }
    typedef game::GameEngine Engine;

而且,引擎.cpp:

#include <iostream>
#include "engine.h"
/* ... */
std::ostream& Engine::operator<<( std::ostream& o, const Engine& engine ) {
    /* ... */
}
当您将

类中的函数声明为友元时,它是封闭命名空间的成员,而不是类本身的成员。所以你需要把它定义为

std::ostream& game::operator<<( std::ostream& o, const Engine& engine ) { ... }

当运算符作为非静态成员函数重载时,它比作为非成员函数(或静态成员函数)少一个参数。这是因为成员版本中有一个隐式参数,即调用对象。所以二元运算符重载,如operator<<,在写为成员时只接受一个参数。调用运算符时,此参数从右侧获取,左侧是调用对象。

这就是为什么错误消息似乎相互矛盾的原因。您在显示的代码中所做的是将您的函数声明为非成员函数(友元不是成员),但您已将其定义为成员函数。

在重载

类的输入和输出流运算符的特定情况下,不能将它们重载为类的非静态成员,因为左侧参数必须是流类。