![](/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.