c++多态之重载
什么是多态?
一种表现,多种实现(多个函数)。
print(x)
1、x为int类型
2、x为float类型
3、x为double类型
c++为什么引入重载?
省事
运算符重载
1、函数重载
代码演示
重载i++、++i、 + 和 +=运算符
#include<iostream>
using namespace std;
class Point
{
friend ostream & operator << (ostream &os, const Point& point);
public:
Point():x(0),y(0)
{}
Point(int a,int b):x(a),y(b)
{}
Point operator+(const Point& p)
{
return Point(this->x += p.x, this->y += p.y);
}
//后置++ i++
Point operator++(int)
{
Point p;
p.x += this->x;
p.y += this->y;
x++;
y++;
return p;
}
//前置++ ++i
Point& operator++()
{
x++;
y++;
return *this;
}
Point& operator +=(const Point& p)
{
this->x += p.x;
this->y += p.y;
return *this;
}
private:
int x;
int y;
};
ostream& operator<<(ostream &os, const Point& point)
{
os << "x:" << point.x << " y:" <<point.y;
return os;
}
int main()
{
Point p1{1,1};
Point p2(3,3);
p1+p2;
cout << p1 <<endl;
p1++;
cout << p1<<endl;
++p2;
cout << p2<<endl;
p1+=p2;
cout << p1 <<endl;
return 0;
}
#include<iostream>
using namespace std;
class Fraction
{
friend ostream & operator << (ostream &os, const Fraction & f);
public:
Fraction(int x,int y):_numerator(x),_denomiantor(y)
{}
int measure(int x,int y)
{
int z=y;
while(x%y!=0)
{
z=x%y;
x=y;
y=z;
}
return z;
}
Fraction operator+(const Fraction& f)
{
int x = this->_numerator * f._denomiantor + this->_denomiantor* f._numerator;
int y= this->_denomiantor * f._denomiantor;
int z = measure(x,y);
return Fraction(x/z,y/z);
}
Fraction operator*(const Fraction& f)
{
int x = this->_numerator * f._numerator;
int y= this->_denomiantor * f._denomiantor;
int z = measure(x,y);
return Fraction(x/z,y/z);
}
Fraction& operator += (const Fraction& f)
{
int x = this->_numerator * f._denomiantor + this->_denomiantor* f._numerator;
int y= this->_denomiantor * f._denomiantor;
int z = measure(x,y);
this->_numerator = x/z;
this->_denomiantor = y/z;
return *this;
}
bool operator == (const Fraction &f)
{
return this->_numerator *f._denomiantor == this->_denomiantor * f._numerator;
}
private:
int _numerator; //分子
int _denomiantor; //分母
};
ostream & operator << (ostream &os, const Fraction & f)
{
os << f._numerator << "/"<< f._denomiantor <<endl;
return os;
}
int main()
{
Fraction f1(1,6);
Fraction f2(1,4);
cout<<(f1+f2) <<endl;
cout<< f1*f2 <<endl;
f1+=f2;
f1*=f2;
if(f1==f2)
cout <<"equ" <<endl;
return 0;
}