运算符重载">>"错误

时间:2016-05-07 15:32:18

标签: c++ operator-overloading

我试图超载>>运营商。我编写了下面的代码用于重载并试图在主要中使用它。我有"没有运营商">>"匹配这些操作数"和c2679错误。我浏览了互联网,但无法找到解决方案。

这是我的操作员过载。

// an array of some unknown items from the database
$array = ['item1','item2','item3'];
$q = array();
foreach ($array as $item) {
    $q[]  = "name contains '$item'";
}

$query['q'] = implode(' and ', $q);

{

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

并尝试在main中使用此代码。

    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;
}

谢谢

2 个答案:

答案 0 :(得分:2)

如果你必须使用指针然后更改

,你试图在这里输入let (<@>) func i = func <*> ??? i 的指针上使用std::cin
Polynomial

std::cin >> newPol1;

最好不要使用指针,只是这样做,

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

答案 1 :(得分:1)

不需要新的:

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
}