这是如何可能在c ++中使用? [英] How is this possible to use in c++?

查看:177
本文介绍了这是如何可能在c ++中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 令我吃惊的是,我发现一个c ++对象的名称可以与类名相同。有人可以向我解释为什么吗?

  2. 当我声明一个类的对象为 (),它不会引发错误,但不会调用构造函数。为什么会发生这种情况?

  1. To my surprise, I found that the name of a c++ object can be the same as class name. Can someone explain to me the reason why?
  2. When I declare an object of class a as a a1(), it does not raise an error, but doesn't call the constructor. Why is this happening?

我的代码:

#include<iostream>
using namespace std;

class a 
{
    public:
    a() 
    {
        cout << "in a\n";
    }
};

int main()
{
    a a1();
    a a;
}


推荐答案

$ c> a a1(); 它实际上被解析为一个函数声明,而不是调用默认构造函数。

When you write a a1(); it is actually being parsed as a function declaration not a call to the default constructor.

a a1;

构造函数

当你写 aa; 时,因为变量名优于类名,所谓的名称隐藏,但即使它的工作,它只会导致混乱,我会避免这样做。

When you write a a; it works because the variable name takes preference over the class name in what is called name hiding, but even though it works it will only lead to confusion and I would avoid doing it.

对于所有喜欢标准报价的人来说,

And for all those people who like standards quotes here you go


可以通过在同一作用域中声明的变量,数据成员,函数或枚举器的名称隐藏类名(9.1)或枚举名(7.2)。如果类或枚举名称和变量,数据成员,函数或枚举器在同一范围(以任何顺序)中声明具有相同的名称,则类或枚举名称在变量,数据成员,函数或枚举器名称可见。

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 ++中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆