简体   繁体   中英

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. 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.

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....

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.

Thanks all, this is the final code, which was compiled smoothly by using mingw-w64 with 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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