当前位置:网站首页>继承中的运算符重载:输入输出的传奇

继承中的运算符重载:输入输出的传奇

2022-08-09 07:59:00 快乐学习吧

他人实验题目
子类继承父类,运算符的重载能继承吗?
**通过实验,结论:**不能继承也不需要继承。
方法分别在子类和父类中声明友函数,在类外分别定义运算符重载。

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

原网站

版权声明
本文为[快乐学习吧]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_47354208/article/details/110726051