科目名稱:程式設計 | 開課系所:資訊工程學系 | 任課教師 |
吳坤熹 |
||
系所別: |
年級: |
學號: |
姓名: |
考試日期 |
2011.3.11 |
(考試時間: 10:30-10:45)
(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).
#include <iostream> // Ex8_02.cpp
#include <cstring> // For strlen() and strcpy()
using std::cout;
using std::endl;
class CMessage
{
private:
char* pmessage; // Pointer to object text string
public:
static int objectCount;
// 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
cout << objectCount << " : " << pmessage << endl;
objectCount++;
}
~CMessage()
{ delete[] pmessage; }
};
int CMessage::objectCount = 0;
void f1()
{
CMessage msg1("Sunday");
CMessage msg2("Monday");
}
void f2()
{
CMessage msg2("Tuesday");
CMessage msg3("Wednesday");
}
int main()
{
f1(); f2();
return 0;
}
(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).
#include <iostream>
using std::cout;
using std::endl;
class CRational
{
public:
int* pnumerator; // 分子
int* pdenominator; // 分母
CRational(int a=0, int b=1)
{
pnumerator = new int;
*pnumerator = a;
pdenominator = new int;
*pdenominator = b;
if (b==0)
{
cout << "Error! The denominator cannot be 0.\n";
exit(1);
}
}
void Print()
{
cout << *pnumerator;
if (*pdenominator != 1)
cout << "/" << *pdenominator;
cout << endl;
}
};
int main()
{
CRational x(1,3);
CRational y(x);
*(y.pdenominator) = 5;
x.Print(); y.Print();
return 0;
}