c++ - 为成员函数中类的枚举成员重载运算符 <<

标签 c++ operator-overloading operator-keyword

如何为作为类成员的枚举重载 << 运算符。具体来说,我有以下代码:

#include <iostream>

using namespace std;

namespace foo {
    class bar {
    public:
        enum a { b, c, d};

        static void print() {
            cout << b << endl;
        }
    };

    ostream& operator<< (ostream& os, bar::a var) {

        switch (var) {
        case bar::b:
            return os << "b";
        case bar::c:
            return os << "c";
        case bar::d:
            return os << "d";
        }
        return os;
    }


}
int main() {
    foo::bar::print();

    return 0;
}

如何让打印函数打印“b”而不是“1”?

最佳答案

这是一个简单的解决方案:

#include <iostream>

using namespace std;

namespace foo {

    class bar {
    public:
        enum a { b, c, d};

        static void print();
    };

    ostream& operator<< (ostream& os, bar::a var) {

        switch (var) {
        case bar::b:
            return os << "b";
        case bar::c:
            return os << "c";
        case bar::d:
            return os << "d";
        }
        return os;
    }


    void bar::print() {
        cout << b << endl;
    }
}
int main() {
    foo::bar::print();

    return 0;
}

[编辑] 正如 aschepler 先前所述,您只需要确保 operator<<(ostream &, bar::a)bar::print 的定义之前可见.

关于c++ - 为成员函数中类的枚举成员重载运算符 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4147854/

相关文章:

c++ - 分支预测 : Writing Code to Understand it; Getting Weird Results

c++ - 将委托(delegate)作为回调传递给 native C++ API 调用

c++ - 在哪里释放函数重载运算符中分配的内存

c++ - 三元运算符的奇怪隐式转换

C++ 运算符重载错误

c++ - 为 Thrust 重载 "+"运算符,有什么想法吗?

c++ - 无法绑定(bind)可变函数并保存到 std::function

c++ - 对结构 vector 进行两次排序

java - 我们可以以编程方式更改语言语法吗?

c++ - 返回一个带有 "return std::set<int>()"的空集 - 它为什么运行?