c ++在同一个类的另一个构造函数中调用构造函数

fni*_*isi 11 c++ gcc constructor c++11

我使用MinGW-w64和4.8.1(带-std = c ++ 11)并尝试在同一个类的另一个构造函数中调用我的类的一个构造函数.不幸的是,我无法编译下面的代码.

A::A(const char *pc) {
  A(string(pc));
}

A::A(string s) {
  vector<string> tmpVector;
  tmpVector.push_back(s);
  A(tmpVector);
}

// Constructor
A::A(vector<string> filePathVector) {
}
Run Code Online (Sandbox Code Playgroud)

以下是GCC抱怨的错误.

In file included from ../parser/nsn/parser.h:37:0,
             from main.cpp:2:
../parser/nsn/parserimp.h: In constructor 'A::A(std::string)':
../parser/nsn/parserimp.h:522:29: error: conflicting declaration 'A  tmpVector'
  A(tmpVector);
                         ^
 ../parser/nsn/parserimp.h:520:17: error: 'tmpVector' has a previous declaration as   'std::vector<std::basic_string<char> > tmpVector'
  vector<string> tmpVector;
Run Code Online (Sandbox Code Playgroud)

我已经在C++ 11中阅读过委托的构造函数概念,但我不确定这是我追求的......

jua*_*nza 26

这个

A(tmpVector);
Run Code Online (Sandbox Code Playgroud)

与此相同

A tmpVector; // but there is already an object called tmpVector
Run Code Online (Sandbox Code Playgroud)

这解释了错误.看起来您想要调用另一个构造函数来初始化同一个对象.在这种情况下,您可以使用委托构造函数:

A::A(string s) : A(vector<string>{s})
{
}
Run Code Online (Sandbox Code Playgroud)

请注意,这是最新的C++ 11语言功能之一,要添加到最流行的编译器中,因此如果您的编译器没有完整的C++ 11语言支持,它可能无法工作.

  • 超过100k代表.这是巨人的史诗般的战斗. (10认同)
  • @MattMcNabb:我问了一个[单独的问题](http://stackoverflow.com/questions/24155571)关于括号问题,并从标准中引用了一个详细的答案,包括你提到的术语. (3认同)
  • @RemyLebeau更多信息,http://stackoverflow.com/questions/24116817/when-do-extra-parentheses-have-an-effect-other-than-on-operator-precedence (2认同)