函数的重载
定义:
作用:函数名可以相同,提高复用性
满足条件:
同一个作用域下
函数名称相同
函数参数类型不同,或者个数不同,或者顺序不同
注意:函数的返回值不可以作为函数重载的条件
#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");
}