user550738
user550738

Reputation:

How do I correctly use enum in this C++ example?

I have a class something like this with a public enum declared:

// DataStorage.h
class DataStorage
{    
  enum ActionType { ADD, REMOVE };

  public :
    data();
    void update(ActionType action, Data dataItem);
};

And then I have a Main.cc that uses it like so ...

// Main.cc
#include "DataStorage.h"

int main() {
  DataStorage dataStorage;
  Data dataItem("abc123");
  dataStorage.update(ActionType.ADD, dataItem); <<-- error here
}

My problem is when I compile I get this error:

Main.cc:29:18: error: ‘ActionType’ was not declared in this scope

What am I doing wrong? Where should the enum be declared and how should I use it in main?

Thx!

Upvotes: 1

Views: 136

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

The following code should work (and is perfectly fine by means of c++ standards):

// DataStorage.h
class DataStorage
{    
  public :
    enum ActionType { ADD, REMOVE };

    data();
    void update(ActionType action, Data dataItem);
};

  dataStorage.update(DataStorage::ADD, dataItem);

If you want to refer the enum values using the ActionType identifier, use the new enum class feature (would resolve to DataStorage::ActionType::ADD then).

Upvotes: 3

billz
billz

Reputation: 45470

update

dataStorage.update(ActionType.ADD, dataItem);  

to:

dataStorage.update(DataStorage::ADD, dataItem);  

Note: You need to make enum type ActionType public.

class DataStorage
{ 
public :   
    enum ActionType { ADD, REMOVE };

    data();
    void update(ActionType action, Data dataItem);
};

Upvotes: 4

Related Questions