【问题标题】:How is 'A(tmpVector);' the same as 'A tmpVector;'?'A(tmp Vector);' 怎么样?和'AN tmp Vector;'一样吗?
【发布时间】:2014-08-01 01:50:20
【问题描述】:

This question 有这个代码 sn-p:

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&lt;string&gt; tmpVector;冲突:

error: conflicting declaration 'A  tmpVector'
error: 'tmpVector' has a previous declaration as 'std::vector<std::basic_string<char> > tmpVector'

The answer 说:

这个

A(tmpVector);

和这个一样

一个 tmpVector; // 但是已经有一个名为 tmpVector 的对象

添加评论:

在这种情况下,() 是多余的。

我的问题是:为什么括号是多余的? C++11 规范中究竟是什么使之如此?我以前没见过这个。

【问题讨论】:

标签: c++ c++11


【解决方案1】:

来自标准的 §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 )

(其余语法省略)。

特别要注意

  1. ptr-declaratordeclarator
  2. ( ptr-declarator ) 形式的东西是 noptr-declarator,而 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

【讨论】:

  • 谢谢,正是我想要的。
猜你喜欢
  • 2020-07-15
  • 2020-12-27
  • 2014-02-12
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
相关资源
最近更新 更多