您的位置:首页 > 编程语言 > C语言/C++

C++的函数重载

2016-03-06 16:30 453 查看
1.所谓重载:
函数重载就是对已有的函数赋予新的含义,使之实现新的功能,因此同一个函数名就可以用来代替不同功能的函数。
2.声明、定义函数重载时如何解决命名冲突问题?
using就是一种解决命名冲突的方法
3 运算符重载实质上就是函数重载
重载运算符的的函数如下:
函数类型 operator 运算符名称(形参表)
{
对运算符的重载处理

}
例如:想对+用于complex的加法运算,函数的原型可以是这样:
complex operator+(complex &c1,complex &c2);
在上面的一般格式中operator是关键字,是专门运用于定义运算符重载函数的,函数名由operator和运算符组成operator+,两个形参是complex类对象的引用,要求实参是complex对象。
4.注重用户体验
有人可能会存在这样的疑虑,既然运算符重载和函数重载一样作用相同何必对运算符重载呢?
这里就要考虑到用户体验,从用户的角度来说虽然运算符重载所实现的功能完全可以由函数实现,但是使用运算符重载能使用户程序易于编写,和阅读维护
5.重载运算符的规则
不能重载的五个运算符:
(1).(成员访问运算符)
(2)*(指针访问运算符)
(3)::(域运算符)
(4)sizeof()(长度运算符)
(5)?:(条件运算符)
前两个运算符不能重载是为了访问成员的功能不能改变,域运算符合sizeof运算符的运算对象时类型,而不是变量或者一般表达式,不具备重载的特征
重载不能改变运算符运算对象的个数,不能改变运算符的优先级,不能改变运算符的结核性,重载运算符不能有默认参数
6为什么运算符重载函数只有一个参数呢?
实际上运算符重载函数应该有两个参数,but重载函数是complex类中的成员函数,因此有一个参数是隐含的,运算符函数是用this指针隐式访问对象中的成员,在这里举个例子吧
complex operator+(complex &c2)
可以看到operator+访问了两个对象成员,一个是形参对象中的成员this->real+c2.real,this->real就是 c1.real。
#include<iostream>
using namespace std;
class complex
{
public:
//定义构造函数
complex(int real=0,int image=0)
{
_real=real;
_image=image;
}

//1声明复数相加函数
complex operator+(complex &c2)
{
complex c;
c._real=_real+c2._real;
c._image=_image+c2._image;
return c;
}

//2声明+=函数
complex &operator+=(const complex &c)
{
this->_real+=c._real;
this->_image+=c._image;
return *this;

}

//3声明前置++函数
complex &operator++()
{
this->_real++;
this->_image++;
return *this;
}

//4声明后置++函数
complex operator++(int)
{
complex tmp(*this);
this->_real++;
this->_image++;
return tmp;
}

//5声明-函数
complex operator-(complex &c2)
{
complex c;
c._real=_real-c2._real;
c._image=_image-c2._image;
return c;
}

//6声明*函数
complex operator*(complex &c2)
{
complex c;
c._real=_real*c2._real-_image*c2._image;
c._image=_image*c2._real+_real*c2._image;
return c;
}
//定义复数输出函数
void display()
{
cout<<_real<<"+"<<_image<<"i"<<endl;
}
private:
int _real;
int _image;

};

int main()
{
//test1
complex c1(3,4),c2(5,6),c3;//定义3个复数对象
c3=c1.operator+(c2);//调用复数相加函数
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c1+c2=";
c3.display();

//	//test2
//complex c1(3,4),c2(2,1);
//c1=c1.operator+=(c2);
//cout<<"c1=";
//c1.display();
//
//	//test3
//complex c1(1,2);
//c1=c1.operator++();
//cout<<"c1=";
//c1.display();
//	//test4
//complex c1(1,2);
//c1=c1.operator++();
//cout<<"c1=";
//c1.display();
//
//	//test5
//complex c1(3,4),c2(1,2),c3;
//c3=c1.operator-(c2);
//cout<<"c1-c2=";
//c3.display();
//
//	//test6
//complex c1(1,2),c2(2,3),c3;
//c3=c1.operator*(c2);
//cout<<"c1*c2=";
//c3.display();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 函数重载