A a()是什么意思? [英] What does A a() mean?
问题描述
请考虑此代码:
#include<iostream>
using namespace std;
class A
{
public:
A():age(12){}
int age;
};
int main()
{
A a();
cout << a.age << endl;
return 0;
}
当我使用g ++编译时,我得到一个错误:
When I compile it using g++, I get an error:
您不能看到成员年龄,因为a不是类A()
you can not see the member age, because a is not a class A()
有人可以向我解释这个吗?什么是 A a()
?
Can someone explain this to me? What is A a()
?
推荐答案
>
This line
A a();
声明一个名为 a
的函数, code> A ,没有参数。 (请参见最讨厌的解析)。
declares a function named a
, returning A
with no arguments. (See Most vexing parse).
你想要的是
A a = A(); // value-initialization
A a{}; // the same but only valid in C++11 (and currently not supported by MSVS)
A a; // default initialization
C ++ 11,§8.5/ 10
C++11, §8.5/10
注意:由于()是初始化语法不允许的,
Note: Since () is not permitted by the syntax for initializer,
X a
不是类X的值初始化对象的声明,而是不带参数并返回X的函数的声明。
is not the declaration of a value-initialized object of class X, but the declaration of a function taking no argument and returning an X.
对于你的类,value-initialization == default-initialization(至少对于结果)。
请参见我的回答: C ++ :通过隐式构造函数初始化int变量用于POD或内置类型的值对于默认初始化的值。
For your class, value-initialization == default-initialization (at least for the outcome). See my answer here: C++: initialization of int variables by an implicit constructor for Infos on value- vs. default-initialization for POD or built-in types.
这篇关于A a()是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!