gpt4 book ai didi

c++ - 如何解决 operator>> 重载错误(不匹配 'operator>>' )

转载 作者:太空狗 更新时间:2023-10-29 20:20:08 26 4
gpt4 key购买 nike

我查看了有关此的其他主题并尝试查看是否可以找到我的错误,但我无法找到解决错误的方法。

我的错误:

no match for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘Polynomial()’)
cin >> p3;

主要内容:

// includes, namespace, etc...

int main()
{
Polynomial p3();

// Prompts user and assigns degrees and coefficients
cout << "Enter the degree followed by the coefficients: ";
cin >> p3;

// other coding
}

运算符的头文件定义>>:

class Polynomial 
{
private:
double *coefs;
int degree;
public:
// constructors, setters/getters, functions
friend std::istream &operator >>(std::istream &in, Polynomial &poly);
};

执行文件:

Polynomial::Polynomial() // default constructor
{
degree = 0;
coefs = new double[1];
coefs[0] = 0.0;
}

std::istream &operator >>(std::istream &in, Polynomial &poly) ////!!!!!!
{
in >> poly.degree;

delete[] poly.coefs; // deallocate memory
poly.coefs = new double[poly.degree + 1]; // create new coefficient array

for(int i = 0; i <= poly.degree; i++) // assigns values into array
{
in >> poly.coefs[i];
}

return in;
}

最佳答案

Polynomial p3(); 是函数声明,而不是变量定义(如您所料)。它声明了一个名为 p3 的函数,该函数返回 Polynomial 并且没有参数。还要注意错误消息,它说操作数类型是 Polynomial(),这是一个函数。

改成

Polynomial p3;

Polynomial p3{}; // since C++11

关于c++ - 如何解决 operator>> 重载错误(不匹配 'operator>>' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53367563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com