Extending QString to overload construction
I would like to extend the QString class from Qt to provide some convenience for converting to/from various string types.
For example, I would like to be able to write lines like:
MyStringClass myString(_T("Hello World!"));
and get a MyStringClass object that behaves just like a QString. Using just QString, that would have had to be written like:
QString myString = QString::fromWCharArray(_T("Hello World!"));
There's other functionality I would like to add to MyStringClass, but I'm getting hung up on how overload the construc开发者_如何转开发tor to accept a wchar_t parameter as in my example. It appears QString's internal data is private, so my derived class can't directly set up the object as necessary (as far as I can tell).
You really aren't abstracting anything there, it's a bad idea. If you bite the bullet and fix it now you won't ever have to deal with it again. If you keep deferring it, the cost will increase as you go.
You really want to keep your basic types as simple as possible.
Having 6 different string types is not manageable either, so narrow it down to QString as soon as possible. If you want help converting the types, write some adapter functions. I've used simple things like the below when converting between QString and std::string for convenience.
std::string sstr(const QString &str);
QString qstr(const std::string &str);
I'm sure you can write similar for the other types you mentioned.
If you really want to write your own class to help with the transition, then you should protect yourself from its continued use. The real risk is that despite its intended deprecation, it is used forever. If you allow your new string class in public interfaces, it will be hard to get rid of. At that point its just another string type to handle with the others.
class MyStringClass {
public:
MyStringClass(const std::string &val);
MyStringClass(const char *val);
MyStringClass(const wchar_t *val);
QString getQString() const;
};
This gives an easy way to get what you need in the new code, and doesn't allow implicit conversions. QString is a value object anyway, not sure you could use it the way you want to.
Chances are you won't convert most of the code, but as long as its in private implementation it won't hurt you that often.
精彩评论