4

I have a QObject class Message and another one named Request that inherits the message class. Here's the header file:

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

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?

4

2 回答 2

10

您需要像这样声明枚举:

enum class RequestTypes
  {
     SetData,
     GetData
  };

为了像你一样使用它,但这需要 C++11。

正常用法是(在您的情况下): r->Type = RequestTypes::SetData;

于 2013-11-14T10:29:00.450 回答
1

哟可以这样使用;

typedef enum 
{
 SetData,
 GetData 
}RequestTypes;
于 2021-06-30T10:28:28.400 回答