This question有以下代码段:
A::A(const char *pc) {
A(string(pc));
}
A::A(string s) {
vector<string> tmpVector;
tmpVector.push_back(s);
A(tmpVector); // <-- error
}
// Constructor
A::A(vector<string> filePathVector) {
}
问题是A(tmpVector);
与vector<string> tmpVector;
冲突:
error: conflicting declaration 'A tmpVector'
error: 'tmpVector' has a previous declaration as 'std::vector<std::basic_string<char> > tmpVector'
此
A(tmpVector);
与此相同
tmpVector; //但是已经存在一个名为tmpVector
的对象
添加评论:
在这种情况下,()是多余的。
我的问题是:为什么括号多余?究竟在C ++ 11规范中究竟是什么呢?我以前没见过。
答案 0 :(得分:15)
来自标准的§8[dcl.decl]:
声明符的语法为:
declarator:
ptr-declarator
noptr-declarator parameters-and-qualifiers trailing-return-type
ptr-declarator:
noptr-declarator
ptr-operator ptr-declarator
noptr-declarator:
declarator-id attribute-specifier-seq_opt
noptr-declarator parameters-and-qualifiers
noptr-declarator [ constant-expression_opt] attribute-specifier-seq_opt
( ptr-declarator )
(遗漏语法的余数)。
特别要注意
ptr-declarator
是declarator
。( ptr-declarator )
形式的某个内容是noptr-declarator
,而ptr-declarator
又是T(x);
。换句话说,你可以拥有任意数量的圆括号,它仍然是一个声明者。现在这会导致像class T {
// ...
public:
T();
T(int);
T(int, int);
};
T(a); // declaration
T(*b)(); // declaration
T(c)=7; // declaration
T(d),e,f=3; // declaration
extern int h;
T(g)(h,2); // declaration
这样的情况模糊不清,这可以通过标准的§6.8[stmt.ambig]来解决:
涉及表达式语句的语法含糊不清 和声明:具有函数样式的表达式语句 显式类型转换(5.2.3),因为它最左边的子表达式可以 与第一个声明者开始的声明无法区分 (a。在这些情况下,声明是声明。
该段所附的例子直接涵盖了这种情况:
{{1}}