國立暨南國際大學 101 學年度第二學期小考試卷                   (考試時間: 14:10-14:20)
科目名稱:程式設計 開課系所:資訊工程 學系 任課教師
吳坤熹
系所別:
年級:
學號:
姓名:
考試日期
2013.3.12
  1. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    // Overloading the Assignment Operator
    #include <iostream>
    using std::endl;
    using std::cout;

    class CData
    {
        public:
            int* pdata;

        CData(int n=0)
        {
            pdata = new(int);
            *pdata = n;
            cout << "Constructor called with initial value " << n << endl;
        }

        ~CData()
        {
            cout << "Destructor called to release the memory storing "
                    << *pdata << endl;
            delete pdata;
        }

        CData& operator=(const CData& d)
        {
            if (this == &d)
               return *this;
            delete pdata;
            pdata = new int;
            *pdata = *(d.pdata);
            return *this;
        }
    };


    int main()
    {
        CData a(3);
        CData b;
        CData c(8);
        a = b = c;
        cout << *(a.pdata) << endl;
        return 0;
    }


  2. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    // Signature of Overloading Functions
    #include <iostream>
    using std::endl;
    using std::cout;

    class CData
    {
        public:
            int* pdata;

        explicit CData(int n=0)
        // What will happen if we omit "explicit"?
        {
            pdata = new(int);
            *pdata = n;
        }

        ~CData()
        {
            delete pdata;
        }

        bool operator!=(const CData& d)
        {
            return *pdata != *(d.pdata);
        }
    };


    int main()
    {
        CData a(3);
        CData b(8);
        CData c(8);
        if (a != b) cout << "Not Equal.\n";
        if (b != 5) cout << "True.\n";
        return 0;
    }