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

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

本文关键字:返回值 结构 可以使 是否      更新时间:2023-10-16

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

例如:

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

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

struct Direction {
    // .. Previous code
    operator FACE () const { return face; }
};

现场示例

您可以

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

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

工作示例

或者,如果您想要字符串"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;
}

工作示例