是否可以使结构直接返回值?

时间:2015-01-08 12:49:55

标签: c++ struct enums

我希望能够在调用结构时直接从结构中返回一个值,而不是通过其成员函数访问我想要的内容。这可能吗?

例如:

#include <iostream>

using namespace std;

enum FACE { NORTH, SOUTH, EAST, WEST };

struct Direction {
    FACE face;
};

int main(){
    Direction dir;
    dir.face = EAST;

    cout << dir;  // I want this to print EAST instead of having to do dir.face
}

2 个答案:

答案 0 :(得分:3)

您可以添加转化运算符FACE

struct Direction {
    // .. Previous code

    operator FACE () const { return face; }
};

Live example

答案 1 :(得分:2)

您可以定义<<运算符来执行此操作。

std::ostream& operator<<(std::ostream& os, Direction const& dir)
{
    return os << dir.face;
}

Working example

或者,如果您想要字符串“EAST”而不是枚举

中的int
std::ostream& operator<<(std::ostream& os, Direction const& dir)
{
    std::string face = "";
    switch(dir.face)
    {
    case(NORTH):
        os << "NORTH";
        break;
    case(SOUTH):
        os << "SOUTH";
        break;
    case(EAST):
        os << "EAST";
        break;
    case(WEST):
        os << "WEST";
        break;
    }
    return os << face;
}

Working example