软件设计基础作业

HW3

G:大整数

//Your Code
补全类 BigInt。它代表一个大整数,你可以通过 + 运算符对大整数做加法。

大整数应当以 C 风格字符串的形式存放在成员 data 所指向的内存中。我们已经为这个类实现了operator<<operator>>来实现输入输出。

此外,我们提供了一些工具函数,可供你直接使用:

int add(const char* a, const char* b, char* dest);,若 a 和 b 是存储整数的字符串,则将它们的和存放到 dest 指向的位置。dest 为空指针时,返回期望写入的字符个数(含末尾空字符)。
int itoa(int a, char* dest);,将整数 a 转换到字符串,存储到 dest 中。dest 为空指针时,返回期望写入的字符个数(含末尾空字符)。


int size = add(a, b, nullptr);
char* buffer = new char[size];
add(a, b, buffer);
// 别忘记在合适的地方 delete[] buffer

代码填空:

#include <cstring>
#include <cstdio>
#include <iostream>
#include <utility>
using std::cin, std::cout, std::endl;

int add(const char* a, const char* b, char* dest);
int itoa(int a, char* dest);

class BigInt {
    char* data{};

public:
// 在此处补充你的代码
//
    ~BigInt() {
        delete[] data;
    }

    friend std::istream& operator>>(std::istream& in, BigInt& c);
    friend std::ostream& operator<<(std::ostream& out, const BigInt& c);
};

int main() {
    BigInt a(0), b("0");
    int n;

    cin >> a >> n;
    a = ("0" + a);
    b = n;

    cout << a + b << endl;
    cout << n + a << endl;
    cout << a + n << endl;

    cout << ((b += n) += "10") << endl;
    cout << ++++b << endl;
    cout << b++ << endl;
    cout << b << endl;
}

// 以下是工具函数的实现,不用关心。

#include <algorithm>
#include <iterator>
#include <memory>
#include <string>

int add(const char*a,const char*b,char*d){int
i=std::strlen(a),j=std::strlen(b),k{},c{};auto
r=std::make_unique<char[]>(std::max(i,j)+1);
auto f=[&](auto...a){int s=(...+a);r[k++]=s%
10+48,c=s/10;};while(i&&j)f(a[--i]-48,b[--j]
-48,c);while(i)f(a[--i]-48,c);while(j)f(b[--
j]-48,c);if(c)r[k++]=c+48;if(d)std::copy(&r[
0],&r[k],std::reverse_iterator{d+k}),d[k]=0;
return k+1;}int itoa(int a,char*dest){return
(dest?sprintf(dest,"%d",a):snprintf(nullptr,
0,"%d",a))+1;}std::istream&operator>>(std::
istream&i,BigInt&c){std::string s;i>>s;c=BigInt
(s.c_str());return i;}std::ostream&operator
<<(std::ostream&o,const BigInt&c){return o<<
c.data;}

输入
一行,共两个数。第一个数是大整数 a, 0 < a <= 10420000。第二个数 b 是 int 范围内的正整数。
输出
共七行。
第一行:a + b
第二行:a + b
第三行:a + b
第四行:2b + 10
第五行:2b + 12
第六行:2b + 12
第七行:2b + 13
样例输入
1 2
样例输出
3
3
3
14
16
16
17
提示
你要实现的成员函数包括:
构造函数(复制、转换)
operator=(复制)
operator+ 可以通过“隐藏友元”的方式编写
operator+=
operator++

关键在于,必须实现operator=.我之前粗心,混淆了复制构造和赋值的区别.如果不实现赋值号,对于类内存储new空间的指针的类来说,将进行浅拷贝,这在不经意间就会造成UB.

posted @ 2023-03-26 00:15  LinXiaoshu  阅读(35)  评论(0)    收藏  举报