用简单的A+B问题来诠释“模块化编程”

· · 算法·理论

正文

题目传送门:P1001

我们不妨来看一下这道题吧。也许对你来说,只要以下代码就能解决:

#include <iostream>
using namespace std;
int main() {
    int a, b;
    cin >> a >> b;
    cout << a + b << endl;
    return 0;
}

但,如果变成这道题呢?P1601

你可能会用数组来表示数来解决大数的表达,但是一旦题目要求不再是 A+B,而是什么更复杂的求解,而从int改成用数组表示数会需要改很多代码。

那么看看下面的代码吧:

#include <iostream>
#include <cstdint>
#include <cctype>
#include <cstdlib>

namespace APlusB {
    using namespace std;

    using Int = int32_t;

    class Adding {
        Int a, b;
    public:
        Adding(Int a, Int b) : a(a), b(b) {}

        Int add() {
            return a + b;
        }
    };

    class Program {
        static Int getInt(istream &in) {
            char c;
            Int out = 0;
            bool flag = false;
            c = in.get();
            if (c == '-') {
                flag = true;
            } else if (isdigit(c)) {
                out = c - '0';
            }
            while (isdigit(c = in.get())) {
                out = out * 10 + Int(c - '0');
            }
            return flag ? -out : out;
        }
    public:
        Program() {}

        void run(istream &in, ostream &out) {
            Adding *add = new Adding(getInt(in), getInt(in));
            out << add->add() << endl;
            delete add;
        }
    };
}

int main() {
    APlusB::Program *prog = new APlusB::Program;
    prog->run(std::cin, std::cout);
    delete prog;
    return EXIT_SUCCESS;
}

相信聪明的你已经注意到了:

using Int = int32_t;

它可以等价为:

typedef int32_t Int;

假设有一个类 BigInteger 实现了整型的所有操作,在定义完这个类后,只需改动这行代码:

using Int = BigInteger;

或

typedef BigInteger Int;

而不需要改动大量代码。

那么,void run(istream &in, ostream &out) 又有何意?

如果题目不让你用标准I/O,而是用诸如APlusB.in和APlusB.out这样的I/O文件,则在包含头文件fstream、iomanip的情况下,int main()函数可以这样写:

int main() {
    APlusB::Program *prog = new APlusB::Program;
    std::fstream in, out;
    in.open("APlusB.in", std::ios::in);
    out.open("APlusB.out", std::ios::out);
    prog->run(in, out);
    delete prog;
    return 0;
}

这时候有人问了,为什么不用

FILE *freopen(const char *path, const char *mode, FILE *stream)

呢?

因为,一旦在代码中使用

std::ios_base::sync_with_stdio(false);

来关闭C/C++标准I/O同步设置,则freopen重定向对于C++标准I/O无效。

模块化编程就是让一个模块只做一件事,改代码也只需要改单个模块。

补充:关于头文件cstdlib下的EXIT_SUCCESS及EXIT_FAILURE宏

它们分别表示 0 与 1。之所以推荐在代码中使用这两个宏,是为了用宏来增强代码可读性,为无意义的常数 0 与 1 赋予“正常退出”与“异常退出”的意义。