【问题标题】:C++ no operator matches these operandsC++ 没有运算符匹配这些操作数
【发布时间】:2020-11-22 10:53:58
【问题描述】:

我复制/粘贴了这个控制台应用程序,它是一个银行记录保存系统,我收到一个错误,因为 ">" 运算符没有操作数; if (infile.read(reinterpret_cast<char*>(this), sizeof(*this)) > 0)

它与类型有关吗?我在某处模糊地读到int 需要超载或其他东西。无论如何,idk。

下面是部分代码:

void account_query::read_rec()
{
    ifstream infile;
    infile.open("record.bank", ios::binary);
    if (!infile)
    {
        cout << "Error in Opening! File Not Found!!" << endl;
        return;
    }
    cout << "\n****Data from file****" << endl;
    while (!infile.eof())
    {
        if (infile.read(reinterpret_cast<char*>(this), sizeof(*this)) > 0)
        {
            show_data();
        }
    }
    infile.close();

【问题讨论】:

标签: c++ file-io operator-keyword operands


【解决方案1】:

ifstream::read() 不返回读取的字符数。它返回对自身的引用。

另外,不要使用while (!infile.eof())Why is iostream::eof() inside a loop condition (i.e. while (!stream.eof())) considered wrong?

相反,在读取ifstream 后测试它是否处于良好状态。这可以通过:

if(infile) { ... }

由于infile.read(...) 返回对infile 的引用,这可能是一个可能的解决方法:

cout << "\n****Data from file****" << endl;
while (infile.read(reinterpret_cast<char*>(this), sizeof(*this)))
    show_data();
}

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 2022-01-10
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多