gpt4 book ai didi

c++ - 为什么函数名不能与返回名类型相同?

转载 作者:行者123 更新时间:2023-12-01 14:04:33 25 4
gpt4 key购买 nike

不确定我缺少什么,但是为什么不能编译?

class Game
{
};

class Actor
{
Game* mGame;
Game* Game() { return mGame; }
};

int main()
{
Actor a();

return 0;
}

g++ -std=c++17 main.cpp -o 测试
main.cpp:8:10: error: declaration of ‘Game* Actor::Game()’ changes meaning of ‘Game’ [-fpermissive]
8 | Game* Game() { return mGame; }
| ^~~~
main.cpp:1:7: note: ‘Game’ declared here as ‘class Game’
1 | class Game
|

显然,如果我将函数更改为 GetGame,则没有问题。只是想知道为什么 - 我错过了什么?

谢谢!

最佳答案

由于添加了语言律师标签,并且对于这是否由标准定义似乎存在一些混淆,以下是标准对现有答案的补充说明。

在 [basic.scope.hiding] 中:

If a class name (11.2) or enumeration name (9.6) and a variable, data member, function, or enumerator are declared in the same declarative region (in any order) with the same name (excluding declarations made visible via using-directives (6.4.1)), the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.



此外,在 [class.name] 中,我们发现:

If a class name is declared in a scope where a variable, function, or enumerator of the same name is also declared, then when both declarations are in scope, the class can be referred to only using an elaborated-type-specifier (6.4.4). [Example:


struct stat {
// ...
};

stat gstat; // use plain stat to define variable

int stat(struct stat*); // redeclare stat as function

void f() {
struct stat* ps; // struct prefix needed to name struct stat
stat(ps); // call stat()
}

— end example]



所以,在 f的范围内, stat指的是该名称的函数,而 struct stat (详细的类型说明符)指的是类。

或者在 OP 的示例中,在 Actor 的范围内, Game指的是该名称的(成员)函数,而 class Game (详细的类型说明符)指的是类。

请注意,或者, ::Game可以用来引用类。

最后,在 [class.name] 的更深处,有一个关于编写此类代码的相关引用:

4 [Note: The declaration of a class name takes effect immediately after the identifier is seen in the class definition or elaborated-type-specifier. For example, class A * A; first specifies A to be the name of a class and then redefines it as the name of a pointer to an object of that class. This means that the elaborated form class A must be used to refer to the class. Such artistry with names can be confusing and is best avoided. — end note]



因此,该标准不仅完全涵盖了这种情况 - 它还建议不要编写此类令人困惑的代码。

关于c++ - 为什么函数名不能与返回名类型相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62338137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com