C++ 过载操作员<&书信电报;用于成员函数中类的枚举成员
如何过载以下是一个简单的解决方案:C++ 过载操作员<&书信电报;用于成员函数中类的枚举成员,c++,operator-overloading,operator-keyword,C++,Operator Overloading,Operator Keyword,如何过载以下是一个简单的解决方案: #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) {
#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;
}
#包括
使用名称空间std;
名称空间foo{
分类栏{
公众:
枚举a{b,c,d};
静态无效打印();
};
ostream&operator这里有一个简单的解决方案:
#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;
}
#包括
使用名称空间std;
名称空间foo{
分类栏{
公众:
枚举a{b,c,d};
静态无效打印();
};
ostream&运算符类栏{
公众:
枚举a{b='b',c='c',d='d'};
静态无效打印(){
cout类栏{
公众:
枚举a{b='b',c='c',d='d'};
静态无效打印(){
cout问题是你使用cout的问题是你使用的时候不能保证你的operator@aschepler:这是正确答案。请尝试确保您的operator@aschepler字体这是正确的答案。聪明。我喜欢。但印刷业可能不是唯一想要的地方打印枚举。聪明。我喜欢。但是打印可能不是唯一想打印枚举的地方。
class bar {
public:
enum a { b = 'b', c = 'c', d = 'd' };
static void print() {
cout << char(b) << endl;
}
};
class bar {
public:
enum a { b, c, d };
static void print();
};
ostream& operator<< (ostream& os, bar::a var) {
...
void bar::print()
{
cout << b << endl;
}