c++ - 在 C++ 中使用 set 和 get 枚举

标签 c++ enums

我想尝试调用我的 set 方法来获取枚举中的值这是我的代码:

枚举.h

class OS
{ 
 public:
 enum OSType{WIN,MAC,UNIX,LINUX};
 OStype getOS() const;
 private:
 OSType type;
};

枚举.cpp

auto OS::getOS() const ->OSType
{ return type;
 }


void OS::setOS(OS::OStype t)
{ 
  type = t;
}

现在我想调用main中的方法

 OS test;
 test.setOS();  //what should i write inside this () ?
 test.getOS();  //return the value which was set;

我知道在枚举中以 WIN =0、MAC = 1 开始...但我不能只在里面写一个数字吗? 我如何给出测试中的枚举值?

cout<<test<<endl

这行得通吗?

最佳答案

enum 将其成员的名称引入封闭范围。这意味着在 OS 中,您只需在需要时使用 WINMAC 等。这反过来意味着当您在类范围之外使用它们时,您需要使用范围运算符来访问它们。因此,就像访问类的任何公共(public)静态成员一样,您可以使用 enum

class_name::enum_member_name

或者在你的情况下

OS::MAC

这意味着你调用 setOS 看起来像

OS test;
test.setOS(OS::MAC);

关于c++ - 在 C++ 中使用 set 和 get 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43874892/

相关文章:

c++ - 使用 OpenCV 打开网络摄像头并使用 QLabel 显示它 - 白色窗口

c++ - 多个 CRTP 基类的对齐

swift - 如何在 Swift 中将从枚举接收到的值转换为字符串?

c++ - 如何将枚举转换为 QString?

ruby-on-rails - Rails 4 枚举验证

c++ - 将枚举值转换为 "Enum"和 "Enum Class"中的整数

c++ - 我可以将函数指针 void* 转换为 std::function 吗?

c++ - new int[25,2] 是什么意思?

c++ - 如何仅使用参数包在 C++11 中实现 boost MPL FOLD ?

java - 使用枚举键和不同值类型进行映射