How can my private method access a public enum in C ++?
I would like to know how or to make my public enum payloadTypes
accessible to my private method threshold()
in my next class:
class A {
private:
unsigned int threshold(payloadTypes kindOfPayload,int x,int y);
public:
enum payloadTypes {
INVALID =-1,
TEST=0,
THRESHOLDS,
RX,
};
}
I get this error if I do as above and I don't want to change the scope of my enum to private
error: 'payloadTypes' was not declared
unsigned int threshold (payloadTypes kindOfPayload, int x, int y);
source to share
Your compiler error is roughly thresholdsGetter()
, but your code is roughly threshold()
. If the compiler error is true, then you need to change your prototype:
unsigned int thresholdsGetter(payloadTypes kindOfPayload,int x,int y);
:
unsigned int thresholdsGetter(A::payloadTypes kindOfPayload,int x,int y);
Thus, it A::payloadTypes
permits an enumeration given that it is defined before the function. As mentioned below, transfers cannot be submitted.
If the code you submitted is true, the following conditions are met:
The problem is that when you declare your function, the enum is not declared or defined.
This will work:
class A {
public:
enum payloadTypes {
INVALID =-1,
TEST=0,
THRESHOLDS,
RX,
};
private:
unsigned int threshold(payloadTypes kindOfPayload,int x,int y);
};
However, you cannot forward the enum declaration. More details in Forward enum declaration in C ++ .
source to share
Since it is thresholdsGetter
not part of the class definition, you need to write A::payloadTypes
, not payloadTypes
because Argument dependency lookup cannot come to the rescue.
Alternatively, do you have a typo in your implementation threshold
? You specified thresholdsGetter
according to the compiler error. But despite the fact that Stroustrup says 1, you still need to declare enum
yours before the function in your class definition. If you fix this, your code will work as it is.
1 Please note that
struct foo
{
enum bar {};
void foobar(bar b){}
};
will compile, but
struct foo
{
void foobar(bar b){}
enum bar {};
};
will not be.
source to share
Nothing in C ++ can be used without declaring it before use or forwarding it. This is not a public or private problem at all. The problem is simply that when you use an enum in a function, it hasn't been declared yet. However, an enumeration cannot be forward-declared, so you will have to change the public and private blocks to get it to work.
source to share