when doing
#include <string> class MyString : public std::string { public: MyString() {} };
But the usage below:
MyString s = 'Happy day'; MyString s('Happy Day'); MyString s = (MyString)'Happy day';
neither of them works.
It seems that there’s something to do with constructors/operators declaration/overridding, but can anyone help point out where may I find these resources?
Thanks.
You need to define some constructors for the different types that you want to be able to convert into your strings. These constructors can basically just hand the parameters through to the underlying
std::string.If you don’t manually create them, the compiler creates a default- and a copy-constructor for you:
To allow construction from string literals, you need a constructor that takes a
const char*:A constructor that takes a
const std::string&would also be useful to convertstd::strings to your string type. If you want to avoid implicit conversions of normal strings, you should make itexplicit:(Edited because my original version was full of errors and I can’t delete the accepted answer)