是否可以使结构直接返回值
Is it possible to make a struct return a value directly?
我希望能够在调用结构时直接从结构返回值,而不是通过其成员函数访问我想要的内容。这可能吗?
例如:
#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;
}
工作示例
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 与函数的结构和返回值有关
- 如何在模板类中使用嵌套的结构/类类型作为返回值
- 将私有结构设置为返回值
- 解析一个结构并从C++函数向C#返回值
- stl数据结构的堆栈上输出参数与返回值的效率
- 作为 c++ dll 函数返回值的结构指针
- 是否可以使结构直接返回值
- 封送结构(包含数组)作为返回值
- 从函数返回值:引用vs结构
- 将返回值赋给结构体(c++)
- 返回值函数中结构成员赋值的额外拷贝
- 用结构向量作为返回值的c++函数
- 返回一个小结构的虚拟函数-返回值与输出参数
- 如何根据布尔类型成员函数的返回值调用结构成员函数
- 结构和函数返回值
- c++只赋值函数调用返回的结构体的一部分
- c++函数中动态分配大结构时的返回值选择