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

科目名稱:程式設計 開課系所:資訊工程 學系 任課教師
吳坤熹
系所別:
年級:
學號:
姓名:
考試日期
2009.4.22

(考試時間: 10:10-10:30)


  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).
    // Operator Overloading
    #include <iostream>
    using std::cout;
    using std::endl;

    class CComplex
    {
    public:
    double real;
    double imaginary;

    CComplex(double a = 0.0, double b = 0):
    real(a), imaginary(b)
    { }

    void Show()
    {
    cout << real;
    if (imaginary<0.0)
    cout << imaginary << "i";
    else if
    (imaginary > 0.0)
    cout << "+" << imaginary << "i";
    cout << "\n";
    }

    CComplex operator+(CComplex c)
    {
    CComplex sum;
    sum.real = this->real + c.real;
    sum.imaginary = this->imaginary + c.imaginary;
    return sum;
    }
    };

    int main()
    {
    CComplex c1(1,2);
    CComplex c2(3,0);
    CComplex c3 = c1 + c2;
    c1.Show();
    c2.Show(); // Hint: "cout << 3.0" will display "3".
    c3.Show();
    }









  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).

    #include <iostream>
    #include <cstring>
    using std::cout;
    using std::endl;

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

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

    // Overloaded assignment operator for CMessage objects
    CMessage& operator=(const CMessage& aMess)
    {
    if(this == &aMess) // Check addresses, if equal
    return *this; // return the 1st operand

    // Release memory for 1st operand
    delete[] pmessage;
    pmessage = new char[ strlen(aMess.pmessage) +1];

    // Copy 2nd operand string to 1st
    strcpy(this->pmessage, aMess.pmessage);

    // Return a reference to 1st operand
    return *this;
    }

    // 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
    }

    // Destructor to free memory allocated by new
    ~CMessage()
    {
    delete[] pmessage; // Free memory assigned to pointer
    }
    };

    int main()
    {
    CMessage motto1("Brazil");
    CMessage motto2("India");
    CMessage motto3("Russia");
    CMessage motto4("Vietnam");

    motto3 = motto2 = motto1; // Use new assignment operator

    cout << "motto2 contains - ";
    motto2.ShowIt();
    cout << endl;

    (motto2 = motto3) = motto4;

    cout << "motto2 now contains - ";
    motto2.ShowIt();
    cout << endl;

    return 0;
    }