【问题标题】:Return the enumeration instead of the index [duplicate]返回枚举而不是索引[重复]
【发布时间】:2011-12-16 21:10:31
【问题描述】:

我有一个简单的类,它使用枚举作为“状态”。当我使用getStatus 成员函数时,它确实返回“忙碌”,但是当我打印该值时,它显示一个“1”。如何打印“忙碌”而不是 1?

http://codepad.org/9NDlxxyU演示

#include <iostream>
using namespace std;

enum Status{Idle, Busy};
class text
{
public:
    void SetStatus(Status s);
    Status getStatus();
private:
    Status s;       
};
void text::SetStatus(Status s)
{
    this->s = s;
}
Status text::getStatus()
{
    return this->s;
}

int main()
{
    text myText;
    myText.SetStatus(Busy);
    cout << myText.getStatus() << endl; //outputs 1, should output "Busy"
}

【问题讨论】:

  • 不,@Nicol,这根本不是重复的。这个问题的答案是调用枚举的 ToString 方法,只有 .Net 枚举有,本机 C++ 枚举没有。
  • 不是重复的。 OP 并不要求任何枚举的“自动”方式。他想知道应该做什么才能让这个枚举按需要显示。

标签: c++ enums


【解决方案1】:

一个完整的工作编辑在这里:http://ideone.com/WFo4g

添加:

std::ostream& operator<<(std::ostream& os, const Status status)
{
    switch (status)
    {
        case Idle: return os << "Idle";
        case Busy: return os << "Busy";
        default:   return os << "Status:" << status;
    }

    return os << "<error>";
}

【讨论】:

    【解决方案2】:

    你不能没有进一步的工作。 Busy 只是一个在编译时存在的标识符,以方便您使用。在编译过程中,编译器会将所有出现的它替换为实际值1

    要使其按您的意愿工作,您需要一个额外的数组或从枚举值映射到描述枚举标识符的字符串。

    【讨论】:

    • 哦,那太蹩脚了,有点违背了目的。
    • 一点也不。目的是防止魔法值和错别字。同样的原因,我们有变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多