运算符重载">>"错误

operator overloading ">>" error

本文关键字:gt 错误 重载 运算符      更新时间:2023-10-16

我正在尝试重载>>运算符。我为过载写了下面的代码,并试图在主要部分使用它。我有"无运算符">>"匹配这些操作数"和c2679错误。我浏览了一下互联网,但找不到解决方案。

这是我的操作员过载。

friend istream& operator >> (istream &in, Polynomial &polynomial) 

    in >> polynomial.e;
    if (polynomial.e > 20)
        throw "Bad Input!";
    polynomial.x = new double[polynomial.e];
    for (int i = 0; i < polynomial.e; i++) {
        polynomial.x[i] = 0;
        in >> polynomial.x[i];
    }
    return in;
}

并尝试将其与此代码一起使用。

out << "poly 1" << endl;
Polynomial *newPol1 = new Polynomial();
try {
    cin >> newPol1;
}
catch (char* s)
{
    cout << s << endl;
}

感谢

您正试图在指向此处类型Polynomial的指针上使用std::cin,如果必须使用指针,则更改

std::cin >> newPol1;

std::cin >> (*newPol1);  // dereference pointer

不过,最好不要使用指针,而是直接使用,

Polynomial newPol1;
std::cin >> newPol1;

不需要新的:

Polynomial newPol1;
try {
    std::cin >> newPol1;
}
...

或者,如果您真的想使用动态分配的对象,那么取消引用它

Polynomial *newPol1 = new Polynomial();
try {
    std::cin >> (*newPol1);  // notice the *
}
...

还有一些需要注意的地方。

if (polynomial.e > 20)   // If things go bad.
                         // in a stream it is  more normal 
    throw "Bad Input!";  // to set the bad bit on the stream.
                         // You can set the stream to throw an
                         // exception if required.

所以我本以为:

if (polynomial.e > 20) {
    in.setstate(std::iosbase::failbit);
}

那么用法是:

if (std::cin >> newPol1) {
    // it worked
}
else {
    // it failed
}