第3章 多态性;1、 多态性的概念;2、运算符重载;运算符重载;运算符重载;运算符重载的实质;运算符重载;运算符重载;运算符重载的实现;运算符重载的实现;运算符重载的实现;双目运算符重载;双目运算符重载;#includeiostream
using namespace std;
class complex //复数类声明
{
public: //外部接口
complex(double r=0.0,double i=0.0){real=r;imag=i;} //构造函数
complex operator + (complex c2); //+重载为成员函数
complex operator - (complex c2); //-重载为成员函数
void display(); //输???复数
private:
double real; //复数实部
double imag; //复数虚部
}; ;C/C++程序设计教程--面向对象分册;complex complex::operator -(complex c2) //重载函数实现
{
complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return complex(c.real,c.imag);
};void complex::display()
{ cout(real,imag)endl; }
void main() //主函数
{ complex c1(5,4),c2(2,10),c3; //声明复数类的对象
coutc1=; c1.display();
coutc2=; c2.display();
c3=c1-c2; //使用重载运算符完成复数减法
coutc3=c1-c2=;
c3.display();
c3=c1+c2; //使用重载运算符完成复数加法
coutc3=c1+c2=;
c3.display();
};程序输出的结果为:
c1=(5,4)
c2=(2,10)
c3=c1-c2=(3,-6)
c3=c1+c2=(7,14)
;例 两字符串加法;static char* str;
String String::operator+(const String a)
{ strcpy(str,name);
strcat(str,);
return String(str);
}
void main()
{ str=new char[256];
String demo1(Visual c++);
String demo2(6.0);
demo1.display();
demo2.display();
; String demo3=demo1+demo2;
demo3.display();
String demo4=demo3+Programming.;
demo4.display();
delete str;
}
此程序的运行结果为:
The string is : Visual C++
The string is : 6.0
The string is : Visual C++ 6.0
The string is : Visual C++ Programming.
;运算符友元函数的设计;#includeiostream
using namespace std;
class complex //复数类声明
{
public: //外部接口
complex(double r=0.0,double i=0.0) { real=r; imag=i; } //构造函数
friend complex operator + (complex c1,complex c2); //运算符+重载为友元函数
friend complex operator - (complex c1,complex c2); //运算符-重载为友元函数
void display(); //显示复数的值
private: //私有数据成员
double real;
double imag;
};
;complex operator +(complex c1,complex c2)
//运算符重载友元函数实现
{ return complex(c2.real+c1.real, c2.imag+c1.imag);
}
complex operator -(co
原创力文档

文档评论(0)