且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C/C++---二进制类(运算符号的重载)

更新时间:2022-08-12 19:31:38

【问题描述】
将一个16位二进制数表示成0和1的字符序列,即用一个字符数组来存放这个二进制数。在这个类中设置两个构造函数,一个是传递整数参数的,另一个是传递字符串参数的。因为用户在创建对象时传递的二进制数,可能是以整数形式给出,也可能是以数字串形式给出,系统应该都能接受。另外有一个类型转换函数int(),用来将类类型向整型转换,即将二进制形式的类对象转换为整形数。两个重载运算符“+”,“-”,用来完成两个二进制数之间的加减运算。

class binary { //定义二进制类

char bits[16]; //二进制字模数组

public:

binary(char *); //字符串参数构造函数

binary(int); //整型参数构造函数

friend binary operator +(binary,binary); //重载“+”,友元函数

friend binary operator -(binary,binary); //重载“-”,友元函数

operator int(); //类类型转换函数,成员函数

friend ostream & operator <<(ostream &out, binary &b);//重载“<<”,以二进制形式输出

void print();//以整型形式输出

};

主函数设计如下,请勿修改:

int main(){undefined

binary n1=“1011”;

binary n2=int(n1)+15;

binary n3=n1-binary(7);

cout<<n1<<endl;

cout<<n2<<endl;

cout<<n3<<endl;

cout<<int(n2)+5<<endl;

n2=n2-binary(5);

n2.print();

n3=n3+binary(5);

n3.print();

cout<<int(n3)-5<<endl;

return 0;

}

【样例输出】

0000000000001011

0000000000011010

0000000000000100

31

21

9

4

代码如下

#include<iostream>
#include<string.h>
#include<cmath>
using namespace std;
class binary {
    char bits[16];
public:
    binary(char *s);
    binary(int n);
    friend binary operator+(binary b1, binary b2);
    friend binary operator-(binary b1, binary b2);
    operator int();
    friend ostream & operator<<(ostream &out, binary &b);
    void print();
};
binary::binary(char *s)
{
    int i, size = strlen(s);
    for (i = 0; i < 16 - size; i++)
    {
        bits[i] = '0';
    }
    for (int j = 0; j < size; j++,i++)
    {
        bits[i] = s[j];
    }
}

binary::binary(int n)
{
    int re, i = 0;
    while (n != 0)
    {
        re = n % 2;
        bits[i++] = re + 48;
        n /= 2;
    }
    while (i<16)
    {
        bits[i++] = '0';
    }
    for (int k = 0, j = 15; k < j; k++, j--)
    {
        re = bits[k];
        bits[k] = bits[j];
        bits[j] = re;
    }
}

binary::operator int()
{
    int j = 0, ans = 0;
    for (int i = 15; i >= 0; i--,j++)
    {
        ans += (bits[i] - 48)*pow(2, j);
    }
    return ans;
}

void binary::print()
{
    cout << int(*this) << endl;
}

binary operator+(binary b1, binary b2)
{
    binary temp(int(b1)+int(b2));
    return temp;
}

binary operator-(binary b1, binary b2)
{
    binary temp(int(b1)-int(b2));
    return temp;
}

ostream & operator<<(ostream & out, binary & b)
{
    for (int i = 0; i < 16; i++)
        out << b.bits[i];
    return out;
}

int main()
{
    binary n1 = const_cast<char*>("1011");
    binary n2 = int(n1) + 15;
    binary n3 = n1 - binary(7);
    cout << n1 << endl;
    cout << n2 << endl;
    cout << n3 << endl;
    cout << int(n2) + 5 << endl;
    n2 = n2 - binary(5);
    n2.print();
    n3 = n3 + binary(5);
    n3.print();
    cout << int(n3) - 5 << endl;
    return 0;
}