C++ 用类封装六种位运算符,并以此为基础实现10进制的加法、减法和乘法运算

//建立一个类封装C语言中的6种位运算(函数接口封装)
//给出调用测试
//基于位运算模拟10进制的+、-、3个运算,给出调用调试。
/

6种位运算

& 	按位与

| 	按位或

^ 	按位异或

~ 	取反

<< 	左移

>> 	右移

*/


#include<iostream>
#include<string>
#include<bits/stdc++.h>
using namespace std;

const char* A="Awy";
const char* B="Awh";
const char* C="Awyh";
const char* D="Qf";
const char* E="Zy";
const char* F="Yy";

int m;
int n;
class Wei
{
	public:
		
	int Awy(int a,int b)
	{
		return a&b;
	}
	//
	
	int Awh(int c,int d)
	{
		return c|d;
	}
	//
	
	int Awyh(int e,int f)
	{
		return e^f;
	}
	//
	
	
	int Qf(int g)
	{
		return ~g;
	}
	
	//
	
	int Zy(int h,int i)
	{
		return h<<i;
	}
	//
	
	int Yy(int j, int k)
	{
		return j>>k;
	}	
	//
 };
 
 //加法
int add(int m,int n)
{
	int add=0;
	int flag =0;
	do{
		add=m^n;
		flag=(m&n)<<1;
		m = add;
		n = flag;
	}while(flag);
	
	return m;
 } 

//减法:function add + function subtraction 
int sub(int m,int n)
{
	return add(m,add(~n,1));
 } 

//乘法function multiplication
int mul (int m, int n)
{
	int mul = 0;
	do{
		if(n&1)
		mul = add(mul,m);
		m = m<<1;
		n = n>>1;
	}while(n);
	return mul;
}
///
int main()
{
	char* option;
	option = new char[100];//为option申请空间 

	cout<<"请选择您需要的位运算符号:\nAwy-按位与\tAwh-按位或\tAwyh-按位异或\n Qf-取反 \t Zy-左移 \t Yy-右移"<<endl;
    //scanf("%s",option);
    cin >> option;	
	Wei w;

	if(strcmp(option,A)==0)
	{
	int m;
	int n;
	cout<<"请输入需要输入的两个数字:"<<endl;
	cin>>m;
	cin>>n;
	cout<<"按位与:"<<w.Awy(6,6)<<endl;
}
	else if(strcmp(option,B)==0)
	{
	int m;
	int n;
	cout<<"请输入需要输入的两个数字:"<<endl;
	cin>>m;
	cin>>n;
	cout<<"\n"<<"按位或:"<<w.Awh(6,6)<<endl;
}
	else if(strcmp(option,C)==0)
	{
	int m;
	int n;
	cout<<"请输入需要输入的两个数字:"<<endl;
	cin>>m;
	cin>>n;
	cout<<"\n"<<"按位异或:"<<w.Awyh(6,6)<<endl; 
}
	else if(strcmp(option,D)==0)
	{
	int m;
	int n;
	cout<<"请输入需要输入的两个数字:"<<endl;
	cin>>m;
	cin>>n;
	cout<<"\n"<<"取反"<<w.Qf(6)<<endl; 
}
	else if(strcmp(option,E)==0)
	{
	int m;
	int n;
	cout<<"请输入需要输入的两个数字:"<<endl;
	cin>>m;
	cin>>n;
	cout<<"\n"<<"左移"<<w.Zy(2,2)<<endl; 
}
	else if(strcmp(option,F)==0)
	{
	int m;
	int n;
	cout<<"请输入需要输入的两个数字:"<<endl;
	cin>>m;
	cin>>n;
	cout<<"\n"<<"右移"<<w.Yy(2,2)<<endl;
}
///
	int option1;
	cout<<"输入数字选择您想要的算法:0-加法,1-减法,2-乘法"<<endl; 
	cin>>option1;
	
	//加法
	if(option1==0)
	{	cout<<"请输入需要计算的两个数字"<<endl; 
		cin>>m;
		cin>>n;
		cout<<"计算结果为:"<<add(m,n)<<endl;
	}
	
	//减法 
	else if(option1==1)
	{ 	cout<<"请输入需要计算的两个数字"<<endl; 
		cin>>m;
		cin>>n;
		cout<<"计算结果为:"<<sub(m,n)<<endl;
	}
	
	//乘法 
	else if(option1==2)
	{	cout<<"请输入需要计算的两个数字"<<endl; 
		cin>>m;
		cin>>n;
		cout<<"计算结果为:"<<mul(m,n)<<endl;
	}
	
	system("pause");
	 return 0;
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值