Reputation: 159
For enums within a class...
Incorrect :
class MyClass{
public:
enum kHTTPMethods {GET,PUT,POST}
};
void MyClass::Func(){
kHTTPMethods method = kHTTPMethod.GET;
}
1) Am I right to say this does not work because .
operator can only be use on objects (instances) of a class?
Correct:
void MyClass::Func(){
kHTTPMethods method = GET;
}
2) Am I right to say this is correct because all the elements of the class becomes globally scoped within the class?
Upvotes: 3
Views: 4707
Reputation: 106246
Well, for your first question the issue is that the enumerations are put in the scope of class MyClass
. Anyway, whether or not you have an object, .
wouldn't let you refer to the enumerations, you need ::
to refer to things in a specific scope. The following will compile, but the corrected MyClass::
scope isn't necessary or useful (i.e. you can just say method = GET
because func
is in the same scope as GET
).
class MyClass
{
public:
enum kHTTPMethods {GET,PUT,POST};
void func() {
kHTTPMethods method = MyClass::GET;
}
};
C++11 added an enum class
that puts them in their own nested scope (such that you must prefix them with [...::MyClass::
] kHTTPMethods::
everywhere), but you have to change your code to use that:
class MyClass
{
public:
enum class kHTTPMethods {GET,PUT,POST}; // note "class" after "enum"
void func() {
kHTTPMethods method = kHTTPMethods::GET;
}
};
For your second question, yeah - that's about the size of it, though I'd phrase it as I have above.
Upvotes: 7
Reputation: 3595
For your 1st question, YES. As far as I know, the .
operator is only used on object to access member variables and member methods.
For your 2nd question. YES.
Everything within the brackets of MyClass::Func(){}
has class scope, because of the MyClass:: preceding Func(). Meanwhile, GET
has class scope too. Thus, you can refer to GET
directly.
Upvotes: 1