问题
Possible Duplicate:
Class method and variable with same name, compile error in C++ not in Java?
The G++ compiler would complain when my class member name and member function name are the same. It seems that whenever a variable name happens to be the same as a function name, the compiler would complain.
In Java, it is not the case. I just wonder why the G++ compiler cannot distinguish a variable name from a function name since the function name always comes with a pair of parenthesis.
回答1:
struct Callable
{
void operator()() const { }
};
struct Test
{
void Call() { }
Callable Call;
};
int main()
{
Test x;
x.Call(); // To which 'Call' does this refer?
}
回答2:
Here's two reasons:
- The variable might overload
operator() - One might take the address of, or create references the function (using its name without associated function call
())
In the first case, what would variable() do? in the second, the compiler would have to determine the correct operation by the return type of an operation - which C++ does not allow for all sorts of reasons.
来源:https://stackoverflow.com/questions/8582477/g-compiler-cannot-distinguish-variable-and-function-with-the-same-name