【问题标题】:no matching function for call to ‘std::basic_ifstream<char>::basic_ifstream(QString&)’没有匹配函数调用‘std::basic_ifstream<char>::basic_ifstream(QString&)’
【发布时间】:2020-07-13 23:58:20
【问题描述】:

这是我第一次使用 QString,我不知道如何解决这个错误:

Personanetscape.cpp:16: error: no matching function for call to ‘std::basic_ifstream::basic_ifstream(QString&)’

这是我的 .h

#include <iostream>
#include <fstream>
#include <string>
#include <qstring.h>
#include <qmap.h>

typedef QMap<QString, QString> Map;


class PersonaNetscape
{
  private:
    std::ifstream fileIn;
    Map map;

  public:
    PersonaNetscape(QString nameFileIn);
    ~PersonaNetscape();
    bool personIn(); 
    QString search(QString field); 
};

这是我的 .cpp

#include "Personanetscape.h"


PersonaNetscape::PersonaNetscape(QString nameFileIn)
                : fileIn(nameFileIn) //this is line 16 in my code
{
  if(!fileIn)
    throw nameFileIn;
}

我该如何解决这个问题?

谢谢。

【问题讨论】:

  • Qt 和 std 是两个独立的 API,它们不直接兼容,但 QString 提供了方法 toUtf8()toStdString() 可以帮助您解决问题。
  • 请尝试fileIn(nameFileIn.toStdString().c_str())
  • 谢夫非常感谢,它成功了。
  • Qt 添加了许多在撰写本文时在 C++ 标准库中不可用的东西。同时,std的开发也关闭了。所以,有很多重复的东西(有时有点不同,因为 std 更通用,而 Qt 更面向应用程序)。至少,Qt 开发人员尽了最大的努力为标准类添加合适的适配器。

标签: c++ qstring


【解决方案1】:

使用 QFile 代替 std::ifstream。

我最初选择 QFile 而不是 std::ifstream 的原因是,一般来说,如果我正在编写使用 QString(或另一个 Qt 框架类)的代码,并且还有其他 Qt 框架类可以实现我正在尝试的功能要做(在这种情况下为 QFile),我会更喜欢它,因为它会更容易,而且我不必担心转换类型/奇怪的边缘情况。

Scheff 在使用我完全忽略的 QStrings 时添加了一个更喜欢 QFile 的重要理由。他说:

std::string 实际上与编码无关,其中 QString 提供了与各种编码相互转换的方法,并且 Qt 中字符串的内部处理是通过明确定义的编码完成的。因此,与使用 .toStdString().c_str() 的“hack”相比,使用 QFile 将使应用程序准备好更好地处理编码和语言环境。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多