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?
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*
.
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With