G++ compiler cannot distinguish variable and function with the same name? [duplicate]

断了今生、忘了曾经 提交于 2020-02-02 11:14:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!