【C++】函数/运算符重载

一、函数重载

1、什么是函数重载?

函数名相同,行参列表(类型,个数,顺序)不同的函数,这些函数构成函数重载。

(*注:C语言没有函数重载,C++有)

void print(int a)
{
    cout << "第一个函数调用:";
    cout << a << endl;
}

void print(char c)
{
    cout << "第二个函数调用:";
    cout << c << endl;
}

int main() {
    print(10);
    print('s');
    
}

2、重载的条件

函数名相同的情况下只要参数列表长得不一样就可以重载,如:

        1、参数类型不同

void print(int a)
{
    cout << "第一个函数调用:";
    cout << a << endl;
}

void print(char c)
{
    cout << "第二个函数调用:";
    cout << c << endl;
}

int main() {
    print(10);
    print('s');
    
}

        2、参数个数不同

void print(int a)
{
    cout << "第一个函数调用:";
    cout << a << endl;
}

void print(int a,int b)
{
    cout << "第二个函数调用:";
    cout << a <<" and "<< b << endl;
}

int main() {
    print(10);
    print(12,14);
}

      3、参数顺序不同

void print(int a,char b)
{
    cout << "第一个函数调用:";
    cout << a <<" and "<< b << endl;
}

void print(char a,int b)
{
    cout << "第二个函数调用:";
    cout << a <<" and "<< b << endl;
}

int main() {
    print(10,'s');
    print('a', 14);
}

3、注意事项

只有返回类型不同的同名函数,不能成为重载。

void print(int a,char b)
{
    cout << "第一个函数调用:";
    cout << a <<" and "<< b << endl;
}

int print(int a,char b)//只有返回类型不同会报错
{
    cout << "第二个函数调用:";
    cout << a <<" and "<< b << endl;
}

二、运算符重载

1、什么是运算符重载?

运算符重载就是让c++自带的运算符(如:+、-、*、/、++、--等)实现我们想要的自定义功能。

代码格式:数据类型  operator  运算符(参数){ 代码 }

原先的运算符则么用,重载的运算符就怎么用。

class A
{
	int a=1;
	int b=2;
public:
	A operator+(const A& d)
	{
		A t;
		t.a = a + d.a;
		t.b = b + d.b;
		return t;
	}
};
int main() {
	A a;
	A b;
	A c = a + b;//这里相当于调用a.operator+(b);

运算符的重载亦可以写在类外

class A
{
public:
	int a=1;
	int b=2;
};
//写在类外要注意类成员变量访问权限的问题
A operator+(const A& a, const A& b)
{
	A t;
	t.a = a.a + b.a;
	t.b = a.b + b.b;
	return t;
}

#不能重载的运算符

“ .* ”、“ ? : ”、“ . ”、“ :: ”、“sizeof” 。

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值