國立暨南國際大學 105 學年度第二學期小考試卷

科目名稱:程式設計 開課系所:資訊工程 學系 考試日期 2017.5.24
系所別:
年級:
學號:
姓名:
考試時間 08:10-08:30
  1. (10%) Predict the output of the following code.
    // Public Data Members (P.437)
    #include <iostream>

    class CRect {
    public:
        int left;    int top;
        int right;   int bottom;

        CRect(int L, int T, int R, int B) {
            left = L;        top = T;
            right = R;       bottom = B;
        }

        int Area() {
            return (right-left) * (bottom-top);
        }
    };

    int main()
    {
        CRect a(10, 20, 30, 40);
        std::cout << a.Area() << std::endl;
        CRect* p = &a;
        a.right = 60;
        p->bottom = 70;
        std::cout << p->Area() << std::endl;
        return 0;
    }

  2. (10%) Predict the output of the following code.
    // Overloading the Increment Operators (P.348)
    #include <iostream>

    class CObj {
        char c;
        int n;
    public:
        CObj(char C, int N): c(C), n(N) {} // Initialization list (P.294)

        CObj& operator++() {
            ++c;
            return *this;
        }

        CObj operator++(int) {
            CObj obj(*this);
            n++;
            return obj;
        }

        void Print() {
            std::cout << c << ' ' << n << std::endl;
        }
    };

    int main()
    {
        CObj a('A', 65);    a.Print();
        (++a).Print();
        a++.Print();        a.Print();
        return 0;
    }

  3. (10%) Determine whether the following code is correct or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    // Inheritance in Classes (P.433)
    #include <iostream>

    class CRect {
    public:
        int left;    int top;
        int right;   int bottom;

        CRect(int L, int T, int R, int B) {
            left = L;        top = T;
            right = R;       bottom = B;
        }
    };

    class MyRect : public CRect {
    public:
        // Constructor Operation in a Derived Class (P.440)
        MyRect(int L, int T, int R, int B): CRect(L, T, R, B) {}

        void Move(int dx, int dy) {
            left += dx;       right += dx;
            top += dy;        bottom += dy;
        }

        void Print() {
            std::cout << '(' << left << ',' << top << ")-("
                 << right << ',' << bottom << ")\n";
        }
    };

    int main()
    {
        MyRect bRect(10, 20, 30, 40);
        bRect.Print();
        bRect.Move(10, -5);
        bRect.Print();
        return 0;
    }