我正在尝试创建一个包含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成员变量?
4 回答
您需要初始化列表中的未命名临时值 . 一个简单的改变就是:
你快到了:
应该这样做,使用
std::string
的隐式转换构造函数来自const char*
.更改
至
尝试
str("string")
并删除std :: string位 .或者,您可以在textPanel类上使用默认构造函数来调用字符串构造函数 .