C程序设计课件(第三章).ppt
文本预览下载声明
第3章多态性;3.1多态性的概念;3.2.1 运算符重载;3.2.1 运算符重载概述;3.2.1 运算符重载概述;3.2.1 运算符重载概述;3.2.1 运算符重载概述;3.2.2 运算符重载的实现;3.2.2 运算符重载的实现;3.2.3 双目运算符重载;#include iostream.h
class Complex
{
public:
Complex () { real=image=0; }
Complex (double r, double i)
{ real = r, image = i; }
void Print();
Complex operator + (Complex );
Complex operator + (float);
private:
double real, image;
};;C/C++程序设计教程--面向对象分册;Complex Complex::operator + (float s)
{
Complex t;
t.real=real+s;
t.image=image;
return t;
}
;void main(void)
{
Complex c1(25,50),c2(100,200),c3;
cout"c1="; c1.Print();
cout"c2="; c2.Print();
c3=c1+c2;
cout"c3=c1+c2=";
c3.Print();
c1 = c1 + 200;
cout"c1=";
c1.Print();
};【例3.2】重载“+”运算符为复数类的友元函数,使这个运算符能直接完成两个复数的加法运算,以及一个复数与一个实数的加法运算。
class Complex
{
public:
Complex (double r, double i);
friend Complex operator +(const Complex c1, const Complex c2);
friend Complex operator +(const Complex c1, double t );
private:
double real, image;
};;Complex operator +(const Complex c1, const Complex c2)
{ Complex c(0,0);
c.real = c1.real + c2.real;
c.image = c1.image + c2.image;
return c;
}
Complex operator +(const complex c1, double t )
{ Complex c(0,0);
c.real = c1.real + t;
c.image = c1.image;
return c;
};void main()
{
Complex c1(2.0, 3.0), c2(4.0, -2.0), c3(0,0);
c3 = c1 + c2;
coutc1+c2=;
Print(c3);
c3 = c1 + 5;
coutc1+5=;
Print(c3);
}
;【例3.3】日期类date中采用友元形式重载“+”运算符,实现日期加上一个天数,得到新日期。
static int mon_day[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
class CDate
{
public:
CDate (int m=0,int d=0,int y=0);
void Display() ;
friend CDate operator + (int d, CDate dt); //友元形式重载+运算符
private:
int month, day, year;
};;CDate operator + (int d, CDate dt)
{
dt.day = dt.day + d;
while(dt.day mon_day[dt.month-1])
{// 少一个闰
显示全部