问题
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"))
{
}
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?
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)’:
How do I go about initializing the text_panel_m member variable without using the default constructor?
回答1:
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"))
回答2:
You're almost there:
SimpleWindow::SimpleWindow():
text_panel_m("default value")
{
}
Should do the trick, using std::string
's implicit converting constructor from const char*
.
回答3:
Change
text_panel_m(std::string temp("default value"))
to
text_panel_m(std::string("default value"))
回答4:
try str("string")
and remove the std::string bit.
Alternatively you could have a default constructor on the textPanel class that calls your string constructor.
来源:https://stackoverflow.com/questions/5732820/initializing-member-class-with-non-default-constructor