c++ - 这怎么可能在 C++ 中使用?

标签 c++ class function-declaration variable-initialization

  1. 令我惊讶的是,我发现 c++ 对象的名称可以与类名相同。有人可以向我解释原因吗?
  2. 当我将 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/

相关文章:

我的 createMinHeightBST 函数中的 JavaScript 函数声明范围

javascript - 分配给函数是否会覆盖该函数或创建隐式全局变量?

c++ - 迭代可变模板类型

c++ - VS2010 RC - 调试器中只有 100 个 std::map 元素

c++ WINAPI 共享内存结构数组

c++ - 类对象在 int main() 中是 'undefined'

python - 如何在函数 Python 中调用类

Java - 从反射中排除父类(super class)字段

c++ - 需要以编程方式初始化类变量数组,我该怎么做?

scala - 函数参数: upper bound vs parent class as argument?