重载指函数名相同,函数的参数列表不同(包含参数个数和参数类型),至于返回类型可同可不同。
1.函数重载
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
using namespace std;
void addFun(int a, int b)
{
cout <<"int,int = "<<a + b << endl;
}
void addFun(double a, double b)
{
cout << "double,double = " << a + b << endl;
}
int main()
{
addFun(1, 1);
addFun(1.1, 2.2);
return 0;
}
得到的结果如下:
2.运算符重载
下面是不可重载的运算符列表:
- .:成员访问运算符
- .*, ->*:成员指针访问运算符
- :::域运算符
- sizeof:长度运算符
- ?::条件运算符
- #: 预处理符号
例子如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
class ComplexNumber {
private:
double real;
double image;
public:
ComplexNumber(double real,double image);
ComplexNumber operator+(const ComplexNumber& op1);//运算符重载为成员函数
void print();
double getReal() const;
double getImage() const;
};
ComplexNumber::ComplexNumber(double real, double image)
:real(real),image(image)
{
}
ComplexNumber ComplexNumber::operator+(const ComplexNumber& op1)
{
double real_num = this->real + op1.real;
double image_num = this->image + op1.image;
return ComplexNumber(real_num, image_num);
}
void ComplexNumber::print()
{
cout << real << "+" << image << "i" << endl;
}
double ComplexNumber::getReal() const {
return real;
}
double ComplexNumber::getImage() const {
return image;
}
int main()
{
ComplexNumber cn1(1,2);
ComplexNumber cn2(2,3);
ComplexNumber cn3 = cn1 + cn2;
cn3.print();
return 0;
}
结果为3+5i