c ++在同一类的另一个构造函数中调用构造函数 [英] c++ call constructor within another constructor of the same class

查看:201
本文介绍了c ++在同一类的另一个构造函数中调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MinGW-w64与4.8.1(与-std = c + + 11),并试图调用同一类的另一个构造函数中我的类的一个构造函数。不幸的是,我没有编译下面的代码。

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

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

//构造函数
A :: A(向量< string> filePathVector){
}
pre>

下面是GCC抱怨的错误。

 文件包括从../parser/nsn/parser.h:37:0,
从main.cpp:2:
../parser/nsn/parserimp.h:在构造函数'A :: A(std :: string)':
../parser/nsn/parserimp.h:522:29:error:conflicting declaration'A tmpVector'
A(tmpVector);
^
../parser/nsn/parserimp.h:520:17:错误:'tmpVector'具有先前的声明为'std :: vector< std :: basic_string< char> > tmpVector'
vector< string> tmpVector;

我已经阅读了关于C ++ 11中的委托构造函数概念,但我不知道这是什么

 >  A(tmpVector); 

与此相同

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

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

  A :: A(string s):A (向量< string> {s})
{
}

这是最新的C ++ 11语言特性之一,添加到最流行的编译器,因此如果你的编译器没有完整的C ++ 11语言支持,它可能不工作。


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.

这篇关于c ++在同一类的另一个构造函数中调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆