'A(tmpVector);'如何与"A tmpVector"相同?

How is 'A(tmpVector);' the same as 'A tmpVector;'?

本文关键字:tmpVector 相同      更新时间:2023-10-16

这个问题有以下代码片段:

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规范中究竟是什么让它如此?我以前从未见过这种情况。

来自标准的§8[dcl.dell]:

声明器的语法为:

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 )

(省略语法的剩余部分(。

特别要注意的是,

  1. 3是CCD_ 4
  2. 形式为( ptr-declarator )的事物是noptr-declarator,而CCD_6又是ptr-declarator

换句话说,您可以拥有任意数量的括号,它仍然是一个声明符。现在,这在T(x);这样的情况下会引起歧义,通过标准的§6.8[stmt.ambig]解决

涉及表达语句的语法有歧义和声明:具有函数样式的表达式语句显式类型转换(5.2.3(作为其最左边的子表达式可以是与第一个声明符开始的声明无法区分带有(。在这种情况下,该语句是一个声明。

该段所附的例子直接涵盖了这种情况:

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