c++ - How to implicitly convert Qt objects to QString? -
what's best way of making all of commented code below work in standard c++/qt way?
class { public: a() { } virtual ~a() { } virtual qstring tostring() { return "a"; } }; class b: { public: b() { } ~b() { } qstring tostring() { return "b"; } }; int main(int argc, char *argv[]) { qcoreapplication a(argc, argv); a_; b b_; // qdebug() << a_; // can make work overloading << yes? // qdebug() << b_; // qstring x = a_; // how make work? // qstring y = b_; qstring s = a_.tostring(); // i'm doing @ present qdebug() << b_.tostring(); // i'm doing @ present return a.exec(); }
i have hierarchy of instances of own qt classes derive same base class. i'd turn them strings implicitly in standard way displayed in qt ui:
i can explicitly myself above own standard method tostring
above, it's not implicit , i'd rather follow qt or c++ convention believe there 1 i'm not aware of.
the strings displayed in q*view controls believe means overloading operator <<
won't enough on it's own.
you add so-called conversion function:
struct foo { operator int() { return 5; } }; foo f; int = f; // uses operator convert int
so in case, replace virtual qstring tostring()
virtual operator qstring()
.
that said, implicit operators frowned-upon. not casts frowned upon, you're allowing cast happen implicitly. c++0x allows tack on explicit
conversion functions make sure explicitly cast, don't know compilers support that.
i think you'd better off leaving have, , adding:
// assume qdebug() convertible std::ostream std::ostream& operator<<(std::ostream& stream, const a& val) { stream << val.tostring(); // need make function const, of course return stream; }
and leaving rest explicit.
Comments
Post a Comment