![](/img/trans.png)
[英]Initializing a member class of an object using a non-default constructor in C++
[英]Initializing member class with non-default constructor
我正在嘗試創建一個包含textPanel類的SimpleWindow類的gui:
class textPanel{
private:
std::string text_m;
public:
textPanel(std::string str):text_m(str){}
~textPanel();
};
class SimpleWindow{
public:
SimpleWindow();
~SimpleWindow();
textPanel text_panel_m;
};
SimpleWindow::SimpleWindow():
text_panel_m(std::string temp("default value"))
{
}
我希望能夠使用const char *初始化text_panel_m,它將轉換為std :: string,而不需要創建另一個帶有const char *的構造函數。 我應該用const char *作為參數創建另一個構造函數嗎? 如果我這樣做有沒有辦法減少使用c ++ 0x的冗余構造函數的數量?
使用上面的方法,我在初始化text_panel_m成員變量時遇到了困難。 g ++給了我以下錯誤:
simpleWindow.cpp:49: error: expected primary-expression before ‘temp’
simpleWindow.cpp: In member function ‘bool SimpleWindow::drawText(std::string)’:
如何在不使用默認構造函數的情況下初始化text_panel_m成員變量?
你快到了:
SimpleWindow::SimpleWindow():
text_panel_m("default value")
{
}
應該這樣做,使用std::string
的隱式轉換構造函數來自const char*
。
您需要初始化列表中的未命名臨時值。 一個簡單的改變就是:
SimpleWindow::SimpleWindow():
text_panel_m(std::string("default value"))
更改
text_panel_m(std::string temp("default value"))
至
text_panel_m(std::string("default value"))
嘗試str("string")
並刪除std :: string位。
或者,您可以在textPanel類上使用默認構造函數來調用字符串構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.