我很好奇,为什么不能使用()语法初始化类的数据成员?考虑以下示例:
#include <iostream>
class test
{
public:
void fun()
{
int a(3);
std::cout<<a<<'\n';
}
private:
int s(3); // Compiler error why???
};
int main()
{
test t;
t.fun();
return 0;
}
程序编译失败并给出以下错误。
11 9 [Error] expected identifier before numeric constant
11 9 [Error] expected ',' or '...' before numeric constant
为什么?是什么原因?C ++标准对类数据成员的初始化怎么说?非常感谢您的帮助。谢谢
这只是其中提供的示例之一:
不幸的是,这使得在解析声明时“
(
expression-list)
”形式的初始化程序变得模棱两可:struct S { int i(x); // data member with initializer // ... static int x; }; struct T { int i(x); // member function declaration // ... typedef int x; };
一种可能的解决方案是依赖现有规则,即如果声明可以是对象或函数,那么它就是函数:
struct S { int i(j); // ill-formed...parsed as a member function, // type j looked up but not found // ... static int j; };
一种类似的解决方案是应用另一条仅在模板中使用的现有规则,即如果
T
可以是类型或其他类型,则可以使用其他规则。typename
如果真的是类型,则可以使用“ ”:struct S { int i(x); // unabmiguously a data member int j(typename y); // unabmiguously a member function };
这两种解决方案都引入了许多用户可能会误解的微妙之处(如comp.lang.c ++上的许多问题所证明的那样,为什么
int i();
块作用域中的“ ”未声明默认初始化int
)。本文提出的解决方案是仅允许“
=
initializer-clause ”和“{
initializer-list}
”形式的初始化程序。这解决了大多数情况下的歧义问题。[..]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句