gpt4 book ai didi

c++ - 重载提取和插入运算符 C++

转载 作者:行者123 更新时间:2023-11-30 02:02:55 25 4
gpt4 key购买 nike

你好,我重载了插入和提取运算符。当我运行我的程序时,插入似乎没有输出值,尽管提取将值放入类中。看起来实例的插入 View 中没有任何值。

主要

/ Input Poly
cout << "Input p1: " << endl;
Polynomial P1;
cin >> P1;

// Output Poly
cout << "p1(x) = " << P1 << '\n' << endl;

类函数

//Insertion
ostream& operator<<(ostream& os, Polynomial Poly){

for (int i=0; i < Poly.polyNum; i++) {
os << Poly.poly[i] << " x^" << i;

if(i != Poly.polyNum - 1){
os << " + ";
}
}

return os;
}

//Extraction
istream& operator>>(istream& is, Polynomial Poly){

int numP = 0;
int * tempP;

is >> numP;

tempP = new int [numP+1];

for (int i=0; i < numP; i++) {
is >> tempP[i];
}

Poly.polyNum = numP;

Poly.poly = new int[Poly.polyNum +1];

for (int i=0; i < Poly.polyNum; i++) {
Poly.poly[i] = tempP[i];
}

return is;
}

最佳答案

istream& operator>>(istream& is, Polynomial Poly)

应该是

istream& operator>>(istream& is, Polynomial& Poly)

您现在所做的只是更改您对象的拷贝的成员:

Polynomial P1;
cin >> P1;

P1 在此之后没有修改。

关于c++ - 重载提取和插入运算符 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12623535/

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