我在命名空间的类中有一个私有(private)枚举。我试图重载 I/O 运算符,但我得到的只是编译器提示 Enum 是私有(private)的。来自 this post 的解决方案对我没有任何帮助。这是我的问题的孤立版本。
测试类.h
#include <iostream>
namespace Test
{
class TestClass
{
enum Enum : unsigned int {a = 0, b};
friend std::ostream& operator<<(std::ostream& os, Enum e);
};
std::ostream& operator<<(std::ostream& os, TestClass::Enum e);
};
测试类.cpp
#include "TestClass.h"
std::ostream& operator<<(std::ostream& os, Test::TestClass::Enum e)
{
//do it
}
编译器对此有提示,但当我从命名空间中删除该类时却没有提示,那么我该如何编译它呢?
我在用
g++ -c TestClass.h
编译这个
最佳答案
你cpp文件中的operator不是你声明的friend。 friend 是命名空间的成员,因为它在其中声明的类是成员。
因此也将运算符定义包装在命名空间范围内。或者完全限定定义
std::ostream& Test::operator<<(std::ostream& os, Test::TestClass::Enum e)
{
//do it
}
关于c++ - 无法为命名空间中的私有(private)枚举重载 i/o 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55344919/