Reference to Member Variable in Function declaration in C++?
I'm trying to do something like the following:
class FOO {
voi开发者_开发百科d bar(int& var = m_var) {
// ....
}
int m_var;
};
Why doesn't this compile? Why didn't they program this into the language? Is there any way to mimic this behavior?
This is not allowed because m_var
is a member variable and needs to be accessed through the object.
It would compile successfully if m_var
was a static member of the class.
A simple workaround is calling an overloaded function with same name or another member function through bar()
(which is a member function & has access to m_var
) and pass m_var
as an parameter by reference.It will have the same effect you want to achieve.
I agree, this is a limitation of the language. It can be implemented into compilers (in my humble opinion) with no difficulty.
If you want this behaviour, you have to write:
class FOO
{
void bar(int& var) { ... }
void bar() { this->bar(m_var); }
int m_var;
};
and the extra function call will be inlined by any half-decent compiler, in case you worry about it.
One solution is to to have static-variables, that would act as placeholders:
class FOO
{
private:
static int _ph_m_var;
void bar(int& var = _ph_var)
{
if(&var == &_ph_var) { // Default }
}
};
Declare m_var to be a static const. It will compile and run.
static const int m_var should do the trick
精彩评论