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

科目名稱:資訊系統 與網路導論 開課系所:資訊工程 學系 任課教師
吳坤熹
系所別:
年級:
學號:
姓名:
考試日期
2010.3.17

(考試時間: 15:30-15:40)


  1. (10%) Determine whether the following code has syntax erros or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    // Using a destructor to free memory
    #include <iostream>          // For stream I/O
    #include <cstring>           // For strlen() and strcpy()
    using std::cout;
    using std::endl;

    //Listing 08_01
    class CMessage
    {
      private:
        char* pmessage;                   // Pointer to object text string


      public:

        // Function to display a message
        void Show() const
        {
          cout << endl << pmessage;
        }

        // Constructor definition
        CMessage(const char* text = "Default message")
        {
          pmessage = new char[strlen(text) + 1];   // Allocate space for text
          strcpy(pmessage, text);                  // Copy text to new memory
        }

        ~CMessage();                               // Destructor prototype
    };

    // Listing 08_02
    // Destructor to free memory allocated by new
    CMessage::~CMessage()
    {
      cout << "Destructor called."         // Just to track what happens
           << endl;
      delete[] pmessage;                   // Free memory assigned to pointer
    }

    int main()
    {
      // Declare object
      CMessage m("Good morning");

      // Dynamic object
      CMessage* pM = new CMessage("Good evening");

      m.Show();                // Display 1st message
      pM->Show();              // Display 2nd message
      cout << endl;

      // delete pM;              // Manually delete object created with new
       return 0;
    }