簡體   English   中英

c ++在同一個類的另一個構造函數中調用構造函數

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

我使用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中閱讀過委托的構造函數概念,但我不確定這是我追求的......

這個

A(tmpVector);

與此相同

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

這解釋了錯誤。 看起來您想要調用另一個構造函數來初始化同一個對象。 在這種情況下,您可以使用委托構造函數

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

請注意,這是最新的C ++ 11語言功能之一,要添加到最流行的編譯器中,因此如果您的編譯器沒有完整的C ++ 11語言支持,它可能無法工作。

謝謝大家,這是最終的代碼,通過使用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