Pet*_*McG 4 c++ string qt operator-overloading
使下面所有注释代码以标准C++/Qt方式工作的最佳方法是什么?
class A {
public:
A() { }
virtual ~A() { }
virtual QString toString() { return "A"; }
};
class B: A {
public:
B() { }
~B() { }
QString toString() { return "B"; }
};
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
A a_;
B b_;
// qDebug() << a_; // I can make this work by overloading << yes?
// qDebug() << b_;
// QString x = a_; // How do I make this work?
// QString y = b_;
QString s = a_.toString(); // What I'm doing at present
qDebug() << b_.toString(); // What I'm doing at present
return a.exec();
}
Run Code Online (Sandbox Code Playgroud)
我有自己的Qt类的实例层次结构,它们都来自同一个基类.我想以标准的方式隐式地将它们变成字符串,以便在Qt ui中显示:
我可以像上面那样使用我自己的标准方法自己明确地做到这一点toString
,但它不是隐含的,我宁愿遵循Qt或C++约定,因为我相信有一个我不知道的.
字符串最终将显示在Q*View控件中,我认为这意味着重载operator <<
将不足以支持它自己.
GMa*_*ckG 13
您只需添加一个所谓的转换函数:
struct foo
{
operator int() { return 5; }
};
foo f;
int i = f; // uses operator to convert to int
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下,只需替换virtual QString toString()
为virtual operator QString()
.
也就是说,隐含的运算符通常是不受欢迎的.不仅是演员不赞成,而且现在你允许演员隐式发生.C++ 0x实际上允许我们explicit
使用转换函数来确保我们显式转换,但我不知道哪些编译器支持它.
我认为离开你拥有的东西要好得多,只需添加:
// I assume qDebug() is convertible to std::ostream
std::ostream& operator<<(std::ostream& stream, const A& val)
{
stream << val.toString(); // would need to make function const, of course
return stream;
}
Run Code Online (Sandbox Code Playgroud)
其余的都是明确的.
归档时间: |
|
查看次数: |
5203 次 |
最近记录: |