科目名稱:程式設計 | 開課系所:資訊工程學系 | 任課教師 |
吳坤熹 |
||
系所別: |
年級: |
學號: |
姓名: |
考試日期 |
2011.3.30 |
(考試時間: 16:30-16: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>
using std::cout;
using std::endl;
class CBox // Base class
{
public:
// Function to show the volume of an object
void ShowVolume() const
{
cout << endl
<< "CBox usable volume is " << Volume();
}
// Function to calculate the volume of a CBox object
virtual double Volume() const
{ return m_Length*m_Width*m_Height; }
// Constructor
CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0)
:m_Length(lv), m_Width(wv), m_Height(hv) {}
protected:
double m_Length;
double m_Width;
double m_Height;
};
class CGlassBox: public CBox // Derived with protected specifier
{
public:
// Function to calculate volume of a CGlassBox
// allowing 15% for packing
virtual double Volume() const
{ return 0.5*m_Length*m_Width*m_Height; }
// Constructor
CGlassBox(double lv, double wv, double hv): CBox(lv, wv, hv){}
};
int main()
{
CBox myBox(2.0, 3.0); // Declare a base box
CGlassBox myGlassBox(2.0, 3.0, 4.0); // Declare derived box of same size
CBox* pBox(nullptr); // Declare a pointer to base class objects
pBox = &myBox; // Set pointer to address of base object
pBox->ShowVolume(); // Display volume of base box
pBox = &myGlassBox; // Set pointer to derived class object
pBox->ShowVolume(); // Display volume of derived box
cout << endl;
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;
struct S {
int i; // size 4
char j; // size 1
double k; // size 8
};
struct T {
int i; // size 4
double k; // size 8
char j; // size 1
};
int main() {
cout << "size of S = " << sizeof(S) << endl;
cout << "size of T = " << sizeof(T) << endl;
}