使用 QString 或 std::string 重载方法:调用不明确
我有一个如下所示的类:
class MyClass {
public:
void drawText(const QString& rText);
void drawText(const std::string& rText);
};
我重载了 drawText()
方法,因为我想接受 QString
以及 std::string
。
但是当我写这样的东西时:
MyClass foo;
foo.drawText("Hello");
编译器抱怨对 drawText()
的调用不明确。
据我了解,从 char 数组中,编译器无法在 QString 或 std::string 之间做出决定,因为两者都提供了合适的构造函数。
但是我有没有办法确保用户可以通过传递 QString
或 std::string
来使用 drawText()
方法> 或 char 数组?
I have a class which looks like this :
class MyClass {
public:
void drawText(const QString& rText);
void drawText(const std::string& rText);
};
I overloaded the drawText()
method because I want to accept QString
as well as std::string
.
But when I write something like this :
MyClass foo;
foo.drawText("Hello");
The compiler is complaining that the call to drawText()
is ambiguous.
I understand that from an array of char, the compiler cannot decide between a QString
or a std::string
, because both provide a suitable constructor.
But is there a way for me to make sure the user can use the drawText()
method either by passing a QString
or a std::string
or an array of char ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要回答您的问题,是的:添加另一个需要 const char* 的重载
从 const char* 到 QString 的隐式转换是有问题的,因为它假定输入是 ASCII。我怀疑 Qt 人员希望完全删除该构造函数,但这会破坏源兼容性。如果您想在应用程序中禁用它,可以定义 QT_NO_CAST_FROM_ASCII。
To answer your question, yes: add another overload which takes
const char*
The implicit conversion from
const char*
to QString is problematic because it assumes that the input is ASCII. I suspect the Qt folks would like to remove that constructor altogether but it would break source compatibility. If you want to disable it in your app, you can define QT_NO_CAST_FROM_ASCII.