gpt4 book ai didi

c++ - 自相矛盾的错误消息 - 运算符重载 <<

转载 作者:行者123 更新时间:2023-11-30 03:55:40 25 4
gpt4 key购买 nike

问题

根据我在类里面编写函数的方式,在尝试重载 << 时,我收到了两条相互矛盾的错误消息之一。接线员是我类的 friend 。错误信息如下:

// 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”和其他几个警告标志来编译文件。

代码

engine.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;

并且,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 ) { ... }

关于c++ - 自相矛盾的错误消息 - 运算符重载 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28952543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com