重载运算符>>C++

Overloading operator >> in C++

本文关键字:gt C++ 运算符 重载      更新时间:2023-10-16
#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;
}

i超载输入操作员输入对象。我面临的问题是,当我共同输入两个对象时,第一个对象输入的数据成员更改。

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

您最初分配一个带有零元素的数组。读取对象时,您会读取术语数量,但您并未重新分配术语数组。我个人建议使用合适的容器类型,例如std::vector<term*>或实际上是std::vector<std::shared_ptr<term>>。如果您坚持数组,则需要这样的东西:

std::istream& operator>>(std::istream& in, poly& p)
{
    if (in>>p.no_terms ) {
        std::unique_ptr<term[]> terms(new term[p.no_terms]);
        for(int i= 0; i<p.no_term; i++)
        {
            in >> terms[i].coeff;
            in >> terms[i].exp;
        }
        if (in) {
            delete[] p.term_ptr;
            p.term_ptr = terms.release();
        }
    }
    return in;
}

poly p1, p2;更改为 poly p1(3), p2(3);

p.no_term的值为 3,但是,查看您的poly构造函数:

poly::poly(int d=0)
{
    no_term = d;
    term_ptr = new term[no_term];
}

您正在创建0长度的数组。另外,无需在代码中使用指针。这是使用std::vector<term>的示例:

#include<iostream>
#include <vector>
using namespace std;
class term
{
    public:
    int exp;
    int coeff;  
};
class poly
{
    public:
    std::vector<term> term_vec;
    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) : term_vec(d), no_term(d)
{
}
istream& operator>>(istream& in, poly& p)
{
    in>>p.no_term;
    p.term_vec.resize(p.no_term);
    for(int i= 0; i<p.no_term; i++)
    {
        in>> p.term_vec[i].coeff;
        in>> p.term_vec[i].exp;
    }
    return in;
}
  ostream& operator<<(ostream& out, const poly& p)
   {
    out<<"coeff"<<" "<<"power"<<endl;
    for(int i = 0; i< p.no_term; i++)
    out<<p.term_vec[i].coeff<<" "<<p.term_vec[i].exp<<endl;
    return out;
   }
   int main(void)
 {
    poly p1, p2;
    cin>>p1;
    cin>>p2;
    cout<<p1;
    cout<<p2;
    return 0;   
 }

您的默认构造函数参数d具有值0。然后您致电new term[0]。在您的示例中,指向具有0长度的数组的指针指向同一位置。填写非valiD内存并查看相同的结果后。