why can't class data member has the same name with function member
class A
{
int test;
void test();
}
//can't compile,why?
Re: why can't class data member has the same name with function member
Quote:
Originally Posted by jianmin jin
class A
{
int test;
void test();
}
//can't compile,why?
Because it's against the rules of C++.
Regards,
Paul McKenzie
Re: why can't class data member has the same name with function member
The parameters of the function must be different for function overloading.
Re: why can't class data member has the same name with function member
i think Khun's answer is reasonalble, when you come to the problem of defining opreator for the class, you will see that it is important to keep the datamember and function member diferrent, because you can make a default parameter for the function member!
Re: why can't class data member has the same name with function member
If it were allowed it would not be recommended anyway.
Code:
class MyClass
{
int m;
public:
int m() const { return m; }
void m( int x ) { m=x; }
MyClass ( int x ) : m(x)
{
}
};
If this were legal, what would m(x) in the constructor do? We know it will set member 'm' to value 'x' but would it be an initialisation or a function call?
Re: why can't class data member has the same name with function member
Error in this code:
Code:
class MyClass
{
int n;
public:
int m() const { return n; }
void m( int x ) { n=x; }
MyClass ( int x ) : m(x)
{
}
};
Error:
Quote:
49) : error C2436: 'm' : member function or nested class in constructor initializer list
Please do note that I renamed m variable with n, just for testing this code!
Re: why can't class data member has the same name with function member
Quote:
class A
{
int test;
void test();
}
//can't compile,why?
If that were allowed, what would A::test evaluate to? The integer defined by "int test" or a function pointer pointing to the function declares as "void test()"?
Re: why can't class data member has the same name with function member
Because "&" - AddressOf operator will result to ambiguity.