C++ 的数组和C 语言一样,C++完全兼容C语言的指针,但是会多出一个this指针
==================================================
用C++实现计算器
case1: 基本实现:
#include <iostream>
using namespace std;
int add(int a,int b)
{
return a+b;
}
int minu(int a,int b)
{
return a-b;
}
int mul(int a,int b)
{
return a*b;
}
double divs(int a,int b)
{
return double(a/b);
}
int main()
{
int a,b;
double res;
char calc;
while(1){
cout<<"请输入你的两个操作数:a,b"<<endl;
cin>>a>>b;
cout << "请输入你需要的运算: + - * /" << endl;
cin>>calc;
switch(calc)
{
case '+':
res=add(a,b);
break;
case '-':
res = minu(a,b);
break;
case '*':
res = mul(a,b);
break;
case '/':
res = divs(a,b);
break;
default:
cout<<"运算符输入有误,请重新输入: + - * /"<<endl;
break;
}
cout<<"结果是:"<<res<<endl;
}
return 0;
}
================================
case 2 : Lambda表达式实现简单函数:
int main()
{
int a,b;
double res;
char calc;
auto add = [](int a,int b)->int{return a+b;};
// auto minu = [](int a,int b)->int{return a-b;};
auto mul = [](int a,int b)->int{return a*b;};
auto divs = [](int a,int b)->double{return double(a/b);};
while(1){
cout<<"请输入你的两个操作数:a,b"<<endl;
cin>>a>>b;
cout << "请输入你需要的运算: + - * /" << endl;
cin>>calc;
auto minu = [a,b]()->int{return a-b;};
switch(calc)
{
case '+':
res=add(a,b);
break;
case '-':
res = minu();
break;
case '*':
res = mul(a,b);
break;
case '/':
res = divs(a,b);
break;
default:
cout<<"运算符输入有误,请重新输入: + - * /"<<endl;
break;
}
cout<<"结果是:"<<res<<endl;
}
return 0;
}
注意使用 [a,b] 进行参数捕获的时候应该注意a,b是否被赋值,不要拿未赋值的a,b进行捕获
=========================
case3 : 使用回调函数调用lambda 表达式实现:
// 缺陷 -- 计算除法的时候不能进行double 值的返回,我们的 回调函数 指定了返回值为 int
int calculator(int a,int b, int(*p)(int a,int b))
{
return p(a,b);
}
int main()
{
int a,b;
double res;
char calc;
// auto add = [](int a,int b)->int{return a+b;};
// auto minu = [](int a,int b)->int{return a-b;};
// auto mul = [](int a,int b)->int{return a*b;};
// auto divs = [](int a,int b)->double{return (double)a/b;};
while(1){
cout<<"请输入你的两个操作数:a,b"<<endl;
cin>>a>>b;
cout << "请输入你需要的运算: + - * /" << endl;
cin>>calc;
switch(calc)
{
case '+':
res= calculator(a,b,[](int a,int b)->int{return a+b;});
break;
case '-':
res = calculator(a,b,[](int a,int b)->int{return a-b;});
break;
case '*':
res = calculator(a,b,[](int a,int b)->int{return a*b;});
break;
case '/':
res = calculator(a,b,[](int a,int b)->int{return a/b;});
break;
default:
cout<<"运算符输入有误,请重新输入: + - * /"<<endl;
break;
}
cout<<"结果是:"<<res<<endl;
}
return 0;
}