初始化成员类与非默认构造函数
问题描述:
我试图让这具有包含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(std::string("default value"))
答
变化
text_panel_m(std::string temp("default value"))
到
text_panel_m(std::string("default value"))
答
尝试str("string")
和删除的std :: string位。
或者你可以在调用你的字符串构造函数的textPanel类上有一个默认的构造函数。
答
就快:
应该从const char*
做的伎俩,利用std::string
的隐式转换构造函数。