当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
随机推荐
mysql事务(详解)
MySql homework practice questions
3D精彩案例,清软英泰建成综合轻量化显示平台!
2019 Nanchang Internet Competition Question C, Hello 2019
OpenHarmony轻智能产品开发直播笔记
进程同步与互斥问题纠错
Use of prepareStatement
Non-decreasing Array
P1064 Jin Ming's Budget Plan
Talking about Flask_script
JS基础1
eTS UI开发学习
BIM技术多牛逼?BIM技术在建筑工程行业的四大发展趋势
.net(四) 数据层实现
配置本地yum源仓库
三层交换机原理及配置
EMQ X message server learning record - prepare for the subsequent completion
梅科尔工作室--BP神经网络培训笔记
VMware virtual machine cannot be connected to the Internet after forced shutdown
.net(一)WebService创建