C++ 函数的重载 + 运算符重载

函数的重载
定义:
       作用:函数名可以相同,提高复用性
满足条件:
       同一个作用域下
       函数名称相同
       函数参数类型不同,或者个数不同,或者顺序不同
注意:函数的返回值不可以作为函数重载的条件

#include<iostream>
using namespace std;
void func(){
	cout<<"func的调用"<<endl; 
}
void func(int a){
	cout<<a<<".int的调用"<<endl; 
}
void func(double a){
	cout<<a<<".double的调用"<<endl; 
}
void func(int a,double b){
	cout<<a<<"-"<<b<<".(int a,double b)的调用"<<endl; 
}
int main(){
	func();
	func(1);
	func(2.0);
	func(1,2.0); 
} 

 

函数重载的注意事项:
        当引用作为函数重载条件时候:
        函数重载碰到函数默认参数时候:

#include<iostream>
using namespace std;
//========1.碰见引用时候函数的重载================ 
void func(const int &a){ //限制只读,只能读不能写 
	cout<<a<<".const a的调用"<<endl; 
}
void func(int &a){ //可读可写 
	cout<<a<<".int a的调用"<<endl; 
}

int main(){
	int a = 10; 
	func(a); //调的是(int &a)
	
	func(10);//调的是(constint &a)
	//int &a = 10; × 不合法
	//const int &a = 10 ;√ 合法 	
} 
#include<iostream>
using namespace std;
//========2.碰见默认参数时候函数的重载======C++98===


int main(){

} 

运算符重载:对已有的运算符重新定义,赋予其另一种可能,以适应不同的数据类型

⭐加号运算符重载:
      先行知识:this指针 或  .

//在类中进行重载定义
#include<iostream>
using namespace std;
class Person {
public:
	int age;
	int weight;
	//易错点:运算符的重载写在类的内部,
	//那么调用的时候要用到类内部变量 就要考虑this指针
	Person operator+(Person &p) {
		Person temp;
		temp.age = this->age + p.age;
		temp.weight = this->weight + p.weight;
		return temp;
	}
};
void test01() {
	Person p1, p2;
	p1.age = 10;
	p1.weight = 20;
	p2.age = 30;
	p2.weight = 40;
	Person p3 = p1 + p2;
	cout << p3.age << " " << p3.weight << endl;
}
int main() {
	test01();
	system("pause");
}
//在数据区定义运算符重载(函数)
#include<iostream>
using namespace std;
class Person {
public:
	int age;
	int weight;
};
Person operator+(Person &p1,Person &p2) {
	Person temp;
	temp.age = p1.age+ p2.age;
	temp.weight = p1.weight + p2.weight;
	return temp;
}
void test01() {
	Person p1, p2;
	p1.age = 10;
	p1.weight = 20;
	p2.age = 30;
	p2.weight = 40;
	Person p3 = p1 + p2;
	cout << p3.age << " " << p3.weight << endl;
}
int main() {
	test01();
	system("pause");
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值