目录
一、 什么是C++ 语言的重载?
C++语言提供了两种重载:函数的重载和运算符的重载。下面分别非常简单介绍函数重载和运算符重载:
二、函数重载
所谓函数重载是指完成不同功能的函数可以具有相同的函数名。当然,这种函数的定义必须符合函数重载的规定,举例如下:
#include <iostream>
int abs(int a_ix);
float abs(float a_fx);
double abs(double a_dx);
int main()
{
std::cout << "the absolute value of -3 is " << abs(-3) << std::endl;
std::cout << "the absolute value of -0.5 is " << abs(-0.5) << std::endl;
std::cout << "the absolute value of 0.03 is " << abs(0.03) << std::endl;
return 0;
}
int abs(int a_ix)
{
return (a_ix < 0 ? -a_ix : a_ix );
}
float abs(float a_fx)
{
return (a_fx < 0 ? -a_fx : a_fx );
}
double abs(double a_dx)
{
return (a_dx < 0 ? -a_dx : a_dx );
}
执行结果:
the absolute value of -3 is 3
the absolute value of -0.5 is 0.5
the absolute value of 0.03 is 0.03
例子是比较简单的,函数名一样,参数类型不一样,这在一定程度上,也体现了C++语言对OOP多态性的支持,尽管一提到多态性,一般指的是虚函数的那个多态性。定义重载函数时,要注意以下几点:
a、定义的重载函数必须具有不同的参数个数或不同的参数类型。只有这样编译系统才有可能根据不同的参数去调用不同的重载函数
b、仅返回值不同时,不能定义为重载函数。例如:
float fun(float x)
{
...
}
void fun(float x)
{
...
}
因为在调用函数时,编译器并不关心函数的返回值类型,而是在函数返回时,才涉及到函数的返回值类型。
三、运算符重载
以我自己封装的一个智能指针开场,因为也是因为智能指针,才细致的看了下运算符重载:
#include<iostream>
#include<string>
class person {
public:
person(std::string a_strName, unsigned a_uAge):m_strName(a_strName), m_uAge(a_uAge){}
private:
std::string m_strName;
unsigned m_uAge;
public:
std::string getName(){return m_strName;}
};
template<class T>
class Myauto_ptr{
public:
Myauto_ptr(T* a_pValue);
~Myauto_ptr();
public:
T* operator ->();
private:
T* ptr;
};
template<class T>
Myauto_ptr<T>::Myauto_ptr(T* a_pValue){
ptr = a_pValue;
}
template<class T>
Myauto_ptr<T>::~Myauto_ptr(){
delete ptr;
std::cout << "auto_ptr released" << std::endl;
}
template<class T>
T* Myauto_ptr<T>::operator ->(){
return ptr;
}
int main()
{
Myauto_ptr<person> autoPerson(new person("songbw", 27));
std::cout << autoPerson->getName() << std::endl;
return 1;
}
执行结果:
songbw
auto_ptr released
智能指针至少来说,调用方式要和普通的指针是一样的,所以需要重载运算符->,如上例->运算符的声明、实现和调用如下:
public:
T* operator ->();
template<class T>
T* Myauto_ptr<T>::operator ->(){
return ptr;
}
std::cout << autoPerson->getName() << std::endl;
函数 getName()的调用
autoPerson->getName()
会被解析为
(autoPerson.operator ->())->getName()
参考文献:
Visual C++ 程序设计 张岳新 编著