使用 QString 或 std::string 重载方法:调用不明确

发布于 2025-01-05 01:02:07 字数 591 浏览 2 评论 0原文

我有一个如下所示的类:

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 之间做出决定,因为两者都提供了合适的构造函数。

但是我有没有办法确保用户可以通过传递 QStringstd::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::stringor an array of char ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沉溺在你眼里的海 2025-01-12 01:02:07

要回答您的问题,是的:添加另一个需要 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文