【问题标题】:error: no match for 'operator>>' in 'std::cin >> stopat'错误:“std::cin >> stopat”中的“operator>>”不匹配
【发布时间】:2012-03-02 11:57:43
【问题描述】:

我正在尝试重新使用 C++,这是我很长一段时间以来的第二个程序。一切都编译得很好,直到它到达cin >> stopat;,它返回似乎是一个相当常见的错误:error: no match for 'operator>>' in 'std::cin >> stopat' 我已经查看了一些东西来解释导致这种情况的原因,但我没有真正理解(由于我在编程方面相对缺乏经验)。是什么导致了这个错误,如果我再次遇到它,我该如何解决?

#include <iostream>
#include "BigInteger.hh"

using namespace std;

int main()
{
    BigInteger A = 0;
    BigInteger  B = 1;
    BigInteger C = 1;
    BigInteger D = 1;
    BigInteger stop = 1;
    cout << "How Many steps? ";
    BigInteger stopat = 0;
    while (stop != stopat)
    {
        if (stopat == 0)
        {
            cin >> stopat;
            cout << endl << "1" << endl;
        }
        D = C;
        C = A + B;
        cout << C << endl;
        A = C;
        B = D;
        stop = stop + 1;
    }
    cin.get();
}

编辑:不知何故,我没想到要链接引用的库。他们在这里:https://mattmccutchen.net/bigint/

【问题讨论】:

  • 什么是BigInteger?好像它没有&gt;&gt; 运算符。
  • 什么是 BigInteger?如果是类名,那么肯定没有重载运算符>>。

标签: c++ operators no-match


【解决方案1】:

您尚未向我们展示 BigInteger 的代码,但需要定义一个函数(在 BigInteger.hh 或您自己的代码中),如下所示:

std::istream& operator >>(std::istream&, BigInteger&);

需要实现此函数才能从流中实际获取“单词”并尝试将其转换为 BigInteger。如果幸运的话,BigInteger 将有一个接受字符串的构造函数,在这种情况下,它会是这样的:

std::istream& operator >>(std::istream& stream, BigInteger& value)
{
    std::string word;
    if (stream >> word)
        value = BigInteger(word);
}

编辑:既然您已经指出了正在使用的库,那么您可以执行以下操作。库本身可能应该为您执行此操作,因为它提供了相应的 ostream 运算符,但如果您研究一下,您会发现通用的、库质量的流运算符比我在这里写的更复杂。

#include <BigIntegerUtils.hh>

std::istream& operator >>(std::istream& stream, BigInteger& value)
{
    std::string word;
    if (stream >> word)
        value = stringToBigInteger(word);
}

【讨论】:

  • value = BigInteger(word) 可能涉及不必要的复制,因为BigInteger 类肯定有一个成员函数来解析字符串中的数字(至少如果它提供这样的构造函数是有意义的)。
  • 自从我写下我的答案后,OP 发布了一个指向相关库的链接,所以现在我们可以确定了。我会相应地更新我的答案。
【解决方案2】:

您在此处遗漏的是有关您的 BigInteger 课程的详细信息。为了使用&gt;&gt; 运算符从输入流中读取一个,您需要为您的类定义operator&gt;&gt;(通常称为流提取器)。这就是您得到的编译器错误的含义。

本质上,您需要的是一个如下所示的函数:

std::istream &operator>>(std::istream &is, BigInteger &bigint)
{ 
    // parse your bigint representation there
    return is;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-13
    • 2015-09-09
    • 1970-01-01
    • 2014-07-03
    • 2012-08-04
    • 2011-10-06
    • 1970-01-01
    • 2011-12-10
    相关资源
    最近更新 更多