國立暨南國際大學 101 學年度第二學期小考試卷                   (考試時間: 14:10-14:20)
科目名稱:程式設計 開課系所:資訊工程 學系 任課教師
吳坤熹
系所別:
年級:
學號:
姓名:
考試日期
2013.4.9
  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;        
        }

        ~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(4);
        CData b(0);
        CData c(9);
        (a = b) = c;
        cout << *(a.pdata) << endl;
        return 0;
    }


  2. (10%) Assume that a file "fname.txt" was generated in the previous question. 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).

    // Static data members

    #include <iostream>

    class CData
    {
    public:
        int value;
        static int nCapacity;
        CData(int n): value(n) { --nCapacity; }
    };

    int CData::nCapacity = 4;

    int main()
    {
        CData a(0);
        CData b(9);
        std::cout << a.nCapacity << std::endl;
        return 0;
    }

  3. (10%) Assume that a file "fname.txt" was generated in the previous question. 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).
    // Size of an object
    #include <iostream>
    #include <cstring>

    class CMessage
    {
    public:
    char* str;
    CMessage(char* s)
    {
    str = new char[strlen(s) + 1];
    strcpy(str, s);
    }

    ~CMessage()
    {
    delete str;
    str = NULL;
    }
    };

    int main()
    {
    CMessage city("Taipei");
    std::cout << sizeof(city) << std::endl;
    // Assume that you are running this program on a 32-bit operating system
    std::cout << strlen(city.str) << std::endl;
    return 0;
    }