问题描述
我正在尝试创建一个具有SimpleWindow类的gui,该类包含一个textPanel类:
I'm trying to make a gui which has a SimpleWindow class that contains a textPanel class:
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"))
{
}
我希望能够使用将转换为std :: string的const char *初始化text_panel_m,而无需制作另一个采用const char *的构造函数.无论如何,我是否应该只使用const char *作为参数创建另一个构造函数?如果我这样做的话,有没有一种方法可以减少使用c ++ 0x的冗余构造函数代码的数量?
I want to be able to initialize the text_panel_m using a const char* that gets converted to a std::string without needing to make another constructor that takes a const char*. Should I just create another constructor with const char* as an argument anyway? If I do it this way is there a way to reduce the amount of redundant constructor code using c++0x?
使用上述方法时,我很难初始化text_panel_m成员变量.g ++给我以下错误:
With the approach above I'm having difficulties initializing the text_panel_m member variable. g++ gives me the following error:
simpleWindow.cpp:49: error: expected primary-expression before ‘temp’
simpleWindow.cpp: In member function ‘bool SimpleWindow::drawText(std::string)’:
如何在不使用默认构造函数的情况下初始化text_panel_m成员变量?
How do I go about initializing the text_panel_m member variable without using the default constructor?
推荐答案
您希望在初始化列表中使用未命名的临时值.一个简单的更改就可以做到:
You want an unnamed temporary value in the initializer list. One simple change will do it:
SimpleWindow::SimpleWindow():
text_panel_m(std::string("default value"))
这篇关于用非默认构造函数初始化成员类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!