c++普通函数重载
博主理解就是,函数名一样,但是形参不一样!(形参的 个数、数量不一样!)
#include <iostream>
#include <windows.h>
using namespace std;
void console(string str){
cout<<"你输入的是字符串:" <<str<<endl;
};
void console(int a){
cout<<"你输入的数字:"<< a<<endl;
};
int console(int a,int b){
return (a+b);
}
// 程序的主函数
int main()
{
SetConsoleOutputCP(65001);
console("aaa");
console(321);
int ys=console(1,2);
cout <<ys<<endl;
return 0;
}
c++类函数重载
下面代码看着眼熟是不是? console.log正是web前端的浏览器打印!!!!
#include <iostream>
#include <windows.h>
using namespace std;
class CONSOLE{
public:
void log(string str){
cout<<"你输入的是字符串:" <<str<<endl;
};
void log(int a){
cout<<"你输入的数字:"<< a<<endl;
};
int log(int a,int b){
return (a+b);
}
};
// 程序的主函数
int main()
{
SetConsoleOutputCP(65001);
CONSOLE console;
console.log("aaa");
console.log(321);
int ys=console.log(1,2);
cout <<ys<<endl;
return 0;
}
c++类重载运行符
1、我赋值给两个对象BOX a, BOX b的class里的int a,int b的初始值,
2、然后计算出他们各自的int a乘于int b;
3、然后用BOX a 减去 BOX b,这一步骤就要在class BOX里定义 operator- 告诉类,有这个减号时要做什么操作。然后把函数里处理完的对象返回给BOX c,打印出c的int a乘于int b的结果
#include <iostream>
#include <windows.h>
using namespace std;
class BOX{
int a,b;
public:
BOX(int x=1,int y=1){
a=x;
b=y;
};
BOX operator-(const BOX& b1){//这个-是一个符号,你也可以是其他运算符+ - * / 也就是说c=a+b;时,你要先定义运算符操作的函数,不然会报错
BOX box;
box.a=this->a-b1.a;
box.b=this->b-b1.b;
return box;
};
void ride(){
cout<<a*b<<endl;
};
};
// 程序的主函数
int main()
{
SetConsoleOutputCP(65001);
BOX a(4,5);
BOX b(2,3);
a.ride();
b.ride();
BOX c;
c=a-b;
c.ride();
return 0;
}
上面那个例子是二元运算重载,来看看其他的重载,本来觉得没必要,现在看下其实很有必要写。
一元运算符重载
几元怎么判断的,就是两个参数才能完成这次运算就叫二元,你像i++这种就是1元(个人理解,理解有错评论区留言下,谢谢)
#include <iostream>
#include <windows.h>
using namespace std;
class BOX{
int a;
public:
BOX(int x=1){
a=x;
};
BOX operator-(){//这个-是一个符号,你也可以是其他运算符+ - * / 也就是说c=a+b;时,你要先定义运算符操作的函数,不然会报错
BOX box;
-this->a;//也可以直接写-a
return box;
};
void log(){
cout <<a;
}
};
// 程序的主函数
int main()
{
SetConsoleOutputCP(65001);
BOX a(2);
-a;
a.log();
return 0;
}
关系重载运算符
#include <iostream>
#include <windows.h>
using namespace std;
class BOX{
int a;
public:
BOX(int x=1){
a=x;
};
bool operator >(const BOX& b){//这个-是一个符号,你也可以是其他运算符+ - * / 也就是说c=a+b;时,你要先定义运算符操作的函数,不然会报错
bool val=(this->a)>b.a;
return val;
};
// void log(){
// cout <<a;
// };
};
// 程序的主函数
int main()
{
SetConsoleOutputCP(65001);
BOX a(2);
BOX b(3);
if(a>b){
cout<<"a>b";
}else{
cout<<"a<b";
}
return 0;
}