#include<iostream>
using namespace std;
class term
{
public:
int exp;
int coeff;
};
class poly
{
public:
term* term_ptr;
int no_term;
poly(int d);
friend istream& operator>>(istream& in, poly& p);
friend ostream& operator<<(ostream& out, const poly& p);
friend poly operator+(const poly& p1, const poly& p2);
};
poly::poly(int d=0)
{
no_term = d;
term_ptr = new term[no_term];
}
istream& operator>>(istream& in, poly& p)
{
in>>p.no_term;
for(int i= 0; i<p.no_term; i++)
{
in>>(p.term_ptr+i)->coeff;
in>>(p.term_ptr+i)->exp;
}
return in;
}
我重載輸入操作者輸入的對象。我面臨的問題是,當我輸入兩個對象後,第一個對象輸入的數據成員發生變化。重載操作者在>> C++
int main(void)
{
poly p1, p2;
cin>>p1;
cin>>p2;
cout<<p1;
cout<<p2;
return 0;
}
如果輸入
3
1 1
1 2
1 3
3
1 1
1 2
1 3
輸出我得到的是
1 1
1 2
1 1
1 1
1 2
1 3
輸出操作符的功能是
ostream& operator<<(ostream& out, const poly& p)
{
out<<"coeff"<<" "<<"power"<<endl;
for(int i = 0; i< p.no_term; i++)
out<<(p.term_ptr+i)->coeff<<" "<<(p.term_ptr+i)->exp<<endl;
return out;
}
+1但爲什麼要使用指針呢? 'std :: vector'應該足夠了。 –
Praetorian
@Praetorian:是的,你是對的。我沒有太注意這種類型的實際做法,我不得不承認...... –