Following sample project created by qt creator and contains following files:
1- UsingEnumeration.pro
2- device.h
3- device.cpp
4- main.cpp
UsingEnumeration.pro file contains project configuration.
2- device.h
3- device.cpp
4- main.cpp
UsingEnumeration.pro file contains project configuration.
TEMPLATE = app CONFIG += console CONFIG -= app_bundle CONFIG -= qt SOURCES += main.cpp \ device.cpp HEADERS += \ device.h
device.h header file contains definition for Device class and Status enumeration.
#ifndef DEVICE_H #define DEVICE_H namespace UsingEnumsSample { enum Status { IDLE = 0, ACTIVE = 1, DEAD = 2 }; class Device { public: Device(); void setStatus(Status pStatus); Status getStatus(); private: Status status; }; } #endif // DEVICE_H
device.cpp file contains implementation for Device class. setDevice method accepts an enumerator and assigns the passed value to Device class private enumeration member.
#include "device.h" namespace UsingEnumsSample { Device::Device() { } void Device::setStatus(Status pStatus) { status = pStatus; } Status Device::getStatus() { return status; } }main.cpp method creates a Device instance and calls its setStatus and getStatus methods to set the Status value to the private Status enumeration member.
#include <iostream> #include "device.h" using namespace std; using namespace UsingEnumsSample; int main() { Device device; device.setStatus(ACTIVE); cout << device.getStatus() << endl; device.setStatus(IDLE); cout << device.getStatus() << endl; return 0; }
When the main method is executed, values of the Status member is displayed on the terminal which are consequently 1 and 0 as the program runs.