Dan*_*ish 8 c++ gcc operator-overloading friend language-lawyer
system.h:
#include <iostream>
namespace ss
{
class system
{
private:
// ...
public:
// ...
friend std::ostream& operator<< (std::ostream& out, const system& sys);
};
}
Run Code Online (Sandbox Code Playgroud)
system.cpp:
#include "system.h"
std::ostream& ss::operator<< (std::ostream& out, const ss::system& sys)
{
// print a representation of the ss::system
// ...
return out;
}
Run Code Online (Sandbox Code Playgroud)
使用g ++ 8.30编译上述代码会产生以下输出:
[db@dbPC test]$ LANG=en g++ -Wall -Wextra system.cpp
system.cpp:2:15: warning: 'std::ostream& ss::operator<<(std::ostream&, const ss::system&)' has not been declared within 'ss'
std::ostream& ss::operator<< (std::ostream& out, const ss::system& sys)
^~
In file included from system.cpp:1:
system.h:11:26: note: only here as a 'friend'
friend std::ostream& operator<< (std::ostream& out, const system& sys);
^~~~~~~~
system.cpp: In function 'std::ostream& ss::operator<<(std::ostream&, const ss::system&)':
system.cpp:2:68: warning: unused parameter 'sys' [-Wunused-parameter]
std::ostream& ss::operator<< (std::ostream& out, const ss::system& sys)
~~~~~~~~~~~~~~~~~~^~~
Run Code Online (Sandbox Code Playgroud)
编译器告诉我,该operator<<函数未在namespace中声明ss。但是,它是在该名称空间中声明的。
我也尝试用编译clang++。clang我只抱怨未使用的参数,而不抱怨“不属于名称空间”的问题。
g++警告的原因是什么?这是错误的警告吗?
版本:
g++ (GCC) 8.3.0
clang version: 8.00 (tags/RELEASE_800/final)
Run Code Online (Sandbox Code Playgroud)
您只是错过了声明operator <<in namespace。
请尝试以下操作:
namespace ss
{
std::ostream& operator << (std::ostream& out, const system& sys);
class system
{
private:
// ...
public:
// ...
friend std::ostream& operator<< (std::ostream& out, const system& sys);
};
}
// in cpp
namespace ss
{
std::ostream& operator << (std::ostream& out, const system& sys)
{
// the body
}
}
Run Code Online (Sandbox Code Playgroud)