不能在命名空间中为私有枚举重载i / o运算符

问题描述 投票:1回答:1

我在命名空间中的类中有一个私有枚举。我正在尝试重载I / O运算符,但我得到的只是编译器抱怨Enum是私有的。来自this post的解决方案没有帮助我。这是我的问题的孤立版本。

TestClass.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);
};

TestClass.cpp

#include "TestClass.h"
std::ostream& operator<<(std::ostream& os, Test::TestClass::Enum e)
{
    //do it
}

编译器抱怨这一点,但是当我从命名空间中删除类时不会抱怨,那么如何编译呢?

我正在使用

g ++ -c TestClass.h

编译这个

c++ enums namespaces operator-overloading friend
1个回答
3
投票

cpp文件中的运算符不是您声明的朋友。朋友是命名空间的成员,因为它声明的类是成员。

因此,也将操作符定义包装在命名空间范围内。或者完全符合定义

std::ostream& Test::operator<<(std::ostream& os, Test::TestClass::Enum e)
{
    //do it
}
© www.soinside.com 2019 - 2024. All rights reserved.