当前位置:网站首页>Operator Overloading in Inheritance: A Legend of Input and Output

Operator Overloading in Inheritance: A Legend of Input and Output

2022-08-09 08:09:00 happy learning

other people's experiment
子类继承父类,Operator overloading can inherit?
**通过实验,结论:**Can not inherit nor need to inherit.
方法Declare friend functions in subclasses and superclasses respectively,Define operator overloading separately outside the class.

class Point
{
    
   friend istream&operator >>(istream&in,Point &point_a);
    friend ostream&operator<<(ostream &out,Point &point_a);
};
istream&operator>>(istream&in,Point &point_a)
{
    
    return in;
}
ostream&operator<<(ostream &out,Point &point_a)
{
    
    return out;
}

class Circle:public Point
{
    
    friend istream&operator>>(istream&in, Circle&circle_b);
    friend ostream&operator<<(ostream&out,Circle&circle_b);
};


istream&operator>>(istream&in,Circle &circle_b)
{
    
    return in;
}
ostream&operator<<(ostream &out,Circle &circle_b)
{
    
    return out;
}


完整实例

#include <iostream>

using namespace std;

class Point
{
    
protected:
    int x,y;
public:

    Point (int a,int b)
    {
    
        x=a;
        y=b;
    }
    friend istream&operator >>(istream&in,Point &point_a);
    friend ostream&operator<<(ostream &out,Point &point_a);
};
istream&operator>>(istream&in,Point &point_a)
{
    
    int a,b;
    in>>a>>b;
    point_a.x=a;
    point_a.y=b;
    return in;
}
ostream&operator<<(ostream &out,Point &point_a)
{
    
    out<<"("<<point_a.x<<","<<point_a.y<<")"<<endl;
    return out;
}

class Circle:public Point
{
    
    int r;
public:
    Circle(int m,int n,int k):Point(m,n)
    {
    
        r=k;
    }
    friend istream&operator>>(istream&in, Circle&circle_b);
    friend ostream&operator<<(ostream&out,Circle&circle_b);
};


istream&operator>>(istream&in,Circle &circle_b)
{
    
    int a,b,c;
    in>>a>>b>>c;
    circle_b.x=a;
    circle_b.y=b;
    circle_b.r=c;
    return in;
}
ostream&operator<<(ostream &out,Circle &circle_b)
{
    
    out<<"("<<circle_b.x<<","<< circle_b.y<<")"<<endl;
    out<<circle_b.r<<endl;
    return out;
}

int main()
{
    
    Point p(0,0);

    Circle c(0,0,0);
    cin>>p;
   cin>>c;
   cout<<p;
   cout<<c;
   return 0;
}

原网站

版权声明
本文为[happy learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090759232651.html