是否可以直接使结构 return 成为一个值?

Is it possible to make a struct return a value directly?

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

例如:

#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
}

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

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

您可以添加转换运算符 FACE:

struct Direction {
    // .. Previous code

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

Live example