【问题标题】:Is it possible to make a struct return a value directly?是否可以使结构直接返回值?
【发布时间】:2015-03-06 14:14:29
【问题描述】:

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

例如:

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

【问题讨论】:

  • 您可以提供ostream&amp; operator&lt;&lt;(ostream&amp; , FACE)

标签: c++ struct enums


【解决方案1】:

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

struct Direction {
    // .. Previous code

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

Live example

【讨论】:

  • 这就是我所追求的。抱歉,我快速编写了示例并选择了一个愚蠢的 cout 场景,导致一些人认为我正在尝试获取字符串返回类型,而实际上我只是在此之后。谢谢。
【解决方案2】:

您可以定义 &lt;&lt; 运算符来执行此操作。

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

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多