C++ 如何在 Qt 中使用枚举?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19975196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use enum in Qt?
提问by Alex
I have a QObject class Message
and another one named Request
that inherits the message class. Here's the header file:
我有一个 QObject 类Message
和另一个Request
继承消息类的类。这是头文件:
#ifndef MESSAGE_H
#define MESSAGE_H
#include <QObject>
class Message : public QObject
{
Q_OBJECT
public:
explicit Message(QObject *parent = 0);
QString Source;
QString Destination;
QString Transaction;
QList<QObject> Content;
signals:
public slots:
};
class Request : public Message
{
Q_OBJECT
Q_ENUMS(RequestTypes)
public:
explicit Request();
enum RequestTypes
{
SetData,
GetData
};
RequestTypes Type;
QString Id;
};
#endif // MESSAGE_H
Now I want to create a Request in my code and set Type to SetData. How can I do that? Here's my current code which gives the error "'Request::RequestTypes' is not a class or namespace". The header file from above is included in my main programs header file, so Request
is known and can be created and I can set the other properties - but not the Type
:
现在我想在我的代码中创建一个请求并将类型设置为 SetData。我怎样才能做到这一点?这是我当前的代码,它给出了错误“'Request::RequestTypes' is not a class or namespace”。上面的头文件包含在我的主程序头文件中,所以Request
是已知的并且可以创建,我可以设置其他属性 - 但不是Type
:
Request *r = new Request();
r->Source = "My Source";
r->Destination = "My Destination";
r->Type = Request::RequestTypes::SetData;
In other words: I could as well had taken a QString for the Type
property of a Request
, but it would be nice and safer to do this with an enum. Can someone please show me what's wrong here?
换句话说:我也可以为 a 的Type
属性使用 QString Request
,但使用枚举来做到这一点会更好也更安全。有人可以告诉我这里有什么问题吗?
回答by
You need to declare the enum like so:
您需要像这样声明枚举:
enum class RequestTypes
{
SetData,
GetData
};
in order to use it like you did, but that requires C++11.
为了像您一样使用它,但这需要 C++11。
The normal usage would be (in your case):
r->Type = RequestTypes::SetData;
正常用法是(在您的情况下):
r->Type = RequestTypes::SetData;