|
-
December 3rd, 2004, 02:19 AM
#1
why can't class data member has the same name with function member
class A
{
int test;
void test();
}
//can't compile,why?
-
December 3rd, 2004, 02:44 AM
#2
Re: why can't class data member has the same name with function member
 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
-
December 3rd, 2004, 02:50 AM
#3
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.
-
December 3rd, 2004, 04:31 AM
#4
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!
-
December 3rd, 2004, 08:50 AM
#5
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?
-
December 3rd, 2004, 09:02 AM
#6
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:
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!
Last edited by Ajay Vijay; December 3rd, 2004 at 09:06 AM.
-
December 3rd, 2004, 12:42 PM
#7
Re: why can't class data member has the same name with function member
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()"?
-
December 4th, 2004, 01:26 AM
#8
Re: why can't class data member has the same name with function member
Because "&" - AddressOf operator will result to ambiguity.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|