简体   繁体   English

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

[英]c++ call constructor within another constructor of the same class

I am using MinGW-w64 with 4.8.1 (with -std=c++11) and trying to call one constructor of my class within another constructor of the same class. 我使用MinGW-w64和4.8.1(带-std = c ++ 11)并尝试在同一个类的另一个构造函数中调用我的类的一个构造函数。 Unfortunately, I failed to compile the code below. 不幸的是,我无法编译下面的代码。

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) {
}

Below is the error GCC is complaining about. 以下是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;

I've read about delegated constructor concept in C++11 but I am not sure this is what I am after.... 我已经在C ++ 11中阅读过委托的构造函数概念,但我不确定这是我追求的......

This 这个

A(tmpVector);

is the same as this 与此相同

A tmpVector; // but there is already an object called tmpVector

This explains the error. 这解释了错误。 It looks like you want to call another constructor to initialize the same object. 看起来您想要调用另一个构造函数来初始化同一个对象。 In this case you can use delegating constructors : 在这种情况下,您可以使用委托构造函数

A::A(string s) : A(vector<string>{s})
{
}

Note that this was one of the latest C++11 language features to be added to the most popular compilers, so it may not work if your compiler doesn't have full C++11 language support. 请注意,这是最新的C ++ 11语言功能之一,要添加到最流行的编译器中,因此如果您的编译器没有完整的C ++ 11语言支持,它可能无法工作。

Thanks all, this is the final code, which was compiled smoothly by using mingw-w64 with GCC 4.8.1 谢谢大家,这是最终的代码,通过使用mingw-w64和GCC 4.8.1顺利编译

A::A(const char *p) : A(string(p)) {
}

A::A(string s) : A(vector<string>{s}) {
}

A::A(vector<string> filePathVector) {
 // Do stuff here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM