Reputation: 594
In Java, you can write a constructor for an enum, e.g.
private MyEnum(String name, int val) {
...
}
And then you can write:
public enum MyEnum {
FIRST("A", 10), SECOND("B", 20), THIRD("C", 30);
private MyEnum(String name, int val) {
...
}
}
Is there any way you can do a similar thing for a C++ enum class?
Upvotes: 5
Views: 3096
Reputation: 21
#pragma once
#include <afxwin.h>
#include "winnt.h"
#include "winuser.h"
/// <summary>
// define Style Constants
/// </summary>
enum IS_STYLES {
TB_TEXT_DEFAULT = 0,
TB_TEXT_DOUBLE = 1,
TB_TEXT_INTEGER = 2,
TB_TEXT_CAPTION_ABOVE = 4,
TB_TEXT_CAPTION_LEFT = 8
};
class CTextBox
{
public:
IS_STYLES mStyle;
CString mString;
CTextBox();
CTextBox(
CString string,
IS_STYLES style
);
};
#include "CTextBox.h"
CTextBox::CTextBox(
CString string,
IS_STYLES Style)
:mStyle(Style),mString(string) //init list
{
// body
}
#pragma once
#include <afxwin.h>
#include "CTextBox.h"
class CMainFrame : public CFrameWnd
{
private:
CTextBox mLength; // member objects
IS_STYLES mStyle;
protected:
public:
CObList myBoxes;
CMainFrame(); // Constructor
};
#include "CMainFrame.h"
#include "CTextBox.h"
CMainFrame::CMainFrame() // CMainFrame Constructor
{
/* Create a box that's comprised of an enum and string
CTextBox's constructor
*/
CTextBox box = CTextBox(IS_STYLES(TB_TEXT_DOUBLE|TB_TEXT_CAPTION_LEFT),
"Hello World");
myBoxes.AddHead((CObject*)box); // add box to a CObList collection.
};
Upvotes: 0
Reputation: 21
Yes,you can! Follow below precisely:
declare the enum list (outside of the class)but in the same namespace and naturally give it a name.
in the .h file declare a class with a member value with a type of the defined enum, its name.
also in the .h file create a class overloaded Constructor who's signature includes having the enum type with a default value(also an enum), and must be at the end of the signature and Initialization list.
in the cpp, use the overloaded Constructor that includes the enum, here use the enum value of your choice, from the declared enum list.
also in the cpp, in the Class implementation list, set the Class member's enum value to the enum declared your Constructor's signature(your chosen value).
Enjoy... Not sure how you'd use "more" than 1 value in the Initialization List which would allow you to then be able to use bitwise and, and bitwise or decision making in your Derived / Instantiated Class.
Upvotes: -2
Reputation: 67380
No, C and C++ enums are just a bunch of constants grouped together. C++ enum classes are the same, but to access them you need to add the name of the enum class as a "namespace".
Upvotes: 6