【问题标题】:c++ call constructor within another constructor of the same classc++ 在同一个类的另一个构造函数中调用构造函数
【发布时间】:2014-08-01 01:04:00
【问题描述】:

我正在使用 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) {
}

以下是 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;

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

【问题讨论】:

    标签: c++ gcc c++11 constructor


    【解决方案1】:

    这个

    A(tmpVector);
    

    和这个一样

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

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

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

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

    【讨论】:

    • A(tmpVector);A tmpVector; 有什么区别?
    • 均超过 100k 代表。这是一场史诗般的泰坦之战。
    • @RemyLebeau 更多信息,stackoverflow.com/questions/24116817/…
    • 类似情况; void f(int s);void f(int (s)); 一样,这是很多最麻烦的解析案例的来源
    • @MattMcNabb:我向separate question 询问了括号问题,并得到了详细的答案,其中引用了包含您提到的术语的标准。
    【解决方案2】:

    谢谢大家,这是最终代码,使用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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-12
      • 2012-06-22
      • 1970-01-01
      • 2023-04-03
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多