C++面向对象——函数重载与运算符重载

函数重载

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++运算符重载

一些重载实例

#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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值