矛盾的错误消息 - 运算符重载<<
Contradictory Error Messages - Operator Overloading <<
>问题
根据我在类中编写函数的方式,当尝试以类的朋友身份重载 <<
运算符时,我会收到 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<<
,在写为成员时只接受一个参数。调用运算符时,此参数从右侧获取,左侧是调用对象。
这就是为什么错误消息似乎相互矛盾的原因。您在显示的代码中所做的是将您的函数声明为非成员函数(友元不是成员),但您已将其定义为成员函数。
在重载类的输入和输出流运算符的特定情况下,不能将它们重载为类的非静态成员,因为左侧参数必须是流类。
相关文章:
- C++重载<<具有typedef'd std::vector
- 重载运算符<<:此运算符函数的参数太多
- 在VS 2012上编译,但不使用Netbeans/MinGW-重载<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- C++分离成员流重载<<
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 重载运算符<<用于ostream语法
- 重载operator< & lt;作为会员打印
- Operator< & lt;重载隐藏其他
- 重载& lt; & lt;为什么我得到以下错误
- 重载ostream&时转换错误无效;operator< & lt;
- operator< & lt;在c++中为类中的类重载
- 重载& lt; & lt;用于打印自定义异常的操作符
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多
- 上Ostream & lt; & lt;重载的困惑
- 重载& lt; & lt;为了我的班级
- 使用带有重载<<endl上的运算符
- 重载& lt; & lt;使用命名空间std
- operator< & lt;重载、名称空间和模板