来啦,来啦,它又来啦,咳咳,某人好像不守信用了哈...emmm ,谁都有的嘛,下次,绝对不会了(希望是真的hhh)
第十章 运算符的重载
用函数实现两个复数相加的
complex complex::add(complex&c)
{
complex c2;
c2.real=real+c.real;
c2.image=image+c.image;
return c2;
}
引用方式
c3=c1.add(c2);
用运算符重载实现两个复数相加
complex complex+(complex&c1)
{
Complex c3;
C3.real=real+c1.real;
C3.image=image+c1.image;
Return c3;}//不建立对象也可以
这里要提醒的是成员函数的内置有个变量!
且运算式的第一个是参数且与类的类型相同
引用方式
C3=c1+c2; c1.operator+(c2)
3 规则
已有
不能 * . :: sizeof ?:
优先级 ,个数,结合性,不能默认参数,至少有类对象,=,,&
不能重载
类似于标准数据类型的功能
成员函数或者友元或者两者都不是
4 复数相加函数作为友元函数来实现
Friend complex operator+(complex&c1,complex&c2)
{
Return complex(c1.real+c2.real,c1.image+c2.image)};
注意友元要用两个参数来实现
5复数和整数相加,通过成员函数来实现
Complex complex::operator+(int &i)
{
Return (real+i,image)}
但是只适用于左边为复数右边为整型的情况
如果是友元
Friend complex operator+(int&i,complex %c)
{
Return complex(i+c.real,image)}//要求数据类型对应就行了,不要求第一个一定是类的数据类型
6 必须双目运算符
流插入,流提取
7 必须单目运算符
赋值 下标 函数调用
8 字符串数值比较函数,运算符的重载
声明
friend bool operator >(string &c1,string&c2);
定义
bool operator > (string &c1,string &c2)
{
if(strcmp(c1.p,c2.p)>0)//注意这里的数据引用
return true ;
else
return false;
}
要是三个函数的重载时,数据判断的结果不同而已,其他都相同
如果要进行程序的完善的话,添加一个比较函数
Void compare (string& c1,string&c2)
{
对重载后的运算符进行使用
If(operator>(c1,c2)==1)
怎么...
}
9重载自增运算符
前置++和后置++
#include
using namespace std;
class time
{
private:
int minute;
int sec;
public:
time(){
minute=0;
sec=0;
}
time(int a,int b)
{
minute=a;
sec=b;
}
void display()
{
cout< } time operator++();//定义重载函数 time operator++(int);//定义重载函数 后置 } time time::operator++() { if(++sec>=60) { sec-=60; minute++; } return *this;//返回当前对象值 } time time::operator++(int) { time t(*this);//建立一个临时对象保存当前的值 sec++; if(sec++>=60) { sec-=60; minute++; }//同样的操作 return temp;返回自加前的对象 } 。。。 9 重载流插入和流提取运算符 只能重载为友元函数或者普通函数,不能定义为成员函数 Eg:输出复数 ostream&operator<<(ostream&output,complex&c) { output< Return output; } 这个程序有个bug就是复数的虚部为负数时输出会有错误,要进行程序的修改!!! Cout< 输入复数 istream&operator<<(istream&output,complex&c) { input< Return input; } 10 转换构造函数 将其他对象转换成类的对象,只能有一个参数 Complex(double r) {real=r,image=0} Eg complex(2.3); 类型转换函数 类-另一个数据类型 Operator 类型名 {转换语句} Operator double() { Return real; } 系统需要时会自动调用这些函数建立一个无名的对象 ,先找有没有运算符重载,然后再考虑要不要类型转换的事



