- 令我惊讶的是,我发现 c++ 对象的名称可以与类名相同。有人可以向我解释原因吗?
- 当我将
a
类的对象声明为a a1()
时,它不会引发错误,但不会调用构造函数。为什么会这样?
我的代码:
#include<iostream>
using namespace std;
class a
{
public:
a()
{
cout << "in a\n";
}
};
int main()
{
a a1();
a a;
}
最佳答案
当您编写 a a1();
时,它实际上被解析为函数声明,而不是对默认构造函数的调用。
a a1;
会正确调用默认构造函数
当您编写 a a;
时,它会起作用,因为在所谓的名称隐藏中,变量名优先于类名,但即使它起作用,它也只会导致困惑,我会避免这样做它。
对于所有喜欢标准引用的人来说,你去吧
A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.
关于c++ - 这怎么可能在 C++ 中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19250608/