oj 贵州大学 第四次作业(c++)(运算符重载)第三题

定义一个4位二进制非负整数类Binary,它有4个取值为0或1的数据成员分别表示各位上的数字。

(1)为Binary类重载成员双目运算符“+”,实现二进制整数加法,要考虑进位,高位溢出作截断处理。(例如:1000 + 1000 = 0000)

(2)为Binary类重载运算符“<<”,用于输出4位二进制数字。

(3)定义一个检查数字合法性的成员函数check(),当检查到某一位上的数字不是0或1时函数返回-1,否则返回这个数的十进制非负整数值。

(4)为Binary类定义构造函数和你认为必要的其它成员。

(5)在主函数中对以上函数和运算符进行测试。main函数已经写好,请根据main函数完成该类的设计。

int main(){

    Binary b1(1,0,0,1),b2(1,0,1,0),b3(1,2,3,4);

    cout<<b1.check()<<" "<<b2.check()<<" "<<b3.check()<<endl;

    cout<<b1<<" "<<b2<<endl;

    b1+b2;

    cout<<b1<<endl;

    Binary b4(1,1,1,1);

    b4+b2;

    cout<<b4<<endl;

    return 0;

}

输入描述

本题没有输入

输出描述

按样例输出

提示

你需要提交main函数之外的代码

样例输入  

样例输出

9 5 -1
1001 0101
1110
0100

#include<iostream>
#include<string>
using namespace std;
class Binary {
private:
    int a, b, c, d;
public:
    Binary() { a = 0; b = 0; c = 0; d = 0; }
    Binary(int a, int b, int c, int d)
    {
        this->a = a;
        this->b = b;
        this->c = c; 
        this->d = d;
    }
    friend Binary &operator+( Binary &c1,const Binary &c2)
    {

         c1.a= c1.a + c2.a;
         c1.b = c1.b + c2.b;
         c1.c = c1.c + c2.c;
         c1.d = c1.d + c2.d;
         if (c1.a >= 2)
         {
             c1.a = c1.a % 2;
             c1.b++;
         }
         if (c1.b >= 2)
         {
             c1.b = c1.b % 2;
             c1.c++;
         }
         if (c1.c >= 2)
         {
             c1.c = c1.c% 2;
             c1.d++;
         }
         if (c1.d >= 2)
         {
             c1.d = c1.d % 2;
         }
         return c1;
        
      
    }
        friend ostream& operator<<(ostream & out, const Binary & g)
        {
            out << g.d << g.c << g.b << g.a;
            return out;
        }
 
    int check()
    {
        int num = 0;
        if ((this->d <0) || this->d>1) num=-1;
        else if (this->c <0 || this->c >1) num=-1;
        else if (this->b <0 || this->b >1) num=-1;
        else if (this->a <0 || this->a >1) num=-1;
        else
            num =this-> a + this->b * 2 + this->c * 2 * 2 +this->d * 2 * 2 * 2;
        return num;
    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值