函数重载
1.函数重载是指可以有多个同名的函数,或函数名相同,但参数列表不同(特征标不同)。
2.函数重载满足的条件
(1)在同一个作用域下
(2)函数名称相同
(3)函数的参数类型不同,或者个数不同,或者顺序不同
3.函数的返回值不同(其他情况相同)不可以作为函数重载的条件
4.注意避免出现同时定义以下两个函数的错误
void Swap ( int a , int b );
void Swap ( int& a, int& b);
编译器会认为这两个函数的特征标相同,因而无法做出“究竟应该调用哪个函数”判断。
因为编译器在编译时,会根据参数列表对函数进行重命名。
🌰:
void Swap ( int a , int b );
在编译时函数名会被重命名为 Swap_int_int
void Swap ( int& a, int& b);也是如此。
5.
void Func(int &a);
Func(10); //错误,相当于int &a=10;
void Func(const int &a);
Func(10); //正确,相当于const int &a=10;
运算符重载
1.运算符重载可以作为类成员函数,也可以做全局函数
2.运算重载符不可以改变语法结构
3.运算重载符不可以改变操作数的个数
4.运算重载符不可以改变优先级
5.运算重载符不可以改变结合性。
6.可重载运算符与不可重载运算符(截自菜鸟教程——C++运算符重载)
![](https://img-blog.csdnimg.cn/20200313211853616.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3g1NjgwNTk4ODg=,size_16,color_FFFFFF,t_70)
一些重载实例
#include <iostream>
using namespace std;
class MyInt {
friend ostream& operator<<(ostream& out, MyInt p) {
out << "num1 = " << p.num1 << endl;
out << "num2 = " << p.num2;
return out;
}
private:
int num1;
int num2;
public:
MyInt(int a = 10, int b = 30) {
num1 = a;
num2 = b;
}
MyInt operator+(const MyInt &p) {
MyInt temp;
temp.num1 = this->num1 + p.num1;
temp.num2 = this->num2 + p.num2;
return temp;
}
MyInt operator-(const MyInt& p) {
MyInt temp;
temp.num1 = this->num1 - p.num1;
temp.num2 = this->num2 - p.num2;
return temp;
}
MyInt& operator++() { //左自增,返回引用
num1++;
num2++;
return *this;
}
MyInt operator++(int) { //右自增,返回值,是右值,因此(a++)不可做左值
MyInt temp = *this;
num1++;
num2++;
return temp;
}
bool operator==(const MyInt& p) {
if (this->num1 == p.num1 && this->num2 == p.num2) {
return true;
}
else {
return false;
}
}
bool operator<(const MyInt& p) {
if (this->num1 < p.num1 && this->num2 < p.num2) {
return true;
}
else {
return false;
}
}
};
void test()
{
MyInt iNum(10, 30);
cout << iNum << endl << iNum++ << endl << ++++iNum << endl << iNum << endl;
MyInt iNum01(5, 25);
MyInt iNum02(10, 30);
MyInt iNum03(10, 30);
MyInt iNum04(10, 25);
cout << (iNum01 == iNum02) << endl;
cout << (iNum02 == iNum03) << endl;
cout << (iNum01 < iNum03) << endl;
cout << (iNum01 < iNum04) << endl;
}
int main()
{
test();
return 0;
}
输出结果
num1 = 13
num2 = 33
num1 = 12
num2 = 32
num1 = 12
num2 = 32
num1 = 10
num2 = 30
0
1
1
0