科目名稱:
程式設計 |
第二次期中考 | 開課系所:資工系 | 考試日期 | 2020.4.30 | |
系所別: |
年級: |
學號: |
姓名: |
考試時間 | 08:20-10:00 |
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
(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).
// Software Engineering Observation 12.7
#include <iostream>
#include <string>
using std::string;
using std::cout;
class String {
public:
String(string s): txt(s) { cout << "+S" << txt; }
~String() { cout << "-S" << txt; }
string txt;
};
class Human {
public:
String name;
Human(string s): name(s) { cout << "+H" << name.txt; }
~Human() { cout << "-H" << name.txt; }
};
class Employee : public Human {
public:
Employee(string n, string d): Human(n), department(d) {
cout << "+E" << department.txt;
}
~Employee() { cout << "-E" << department.txt; }
private:
String department;
};
void f1() {
Human a("A");
}
void f2() {
Employee e("E", "F");
f1();
}
int main()
{
Human b("B");
Employee c("C", "D");
cout << '\n';
f2();
cout << '\n';
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).
// Polymorphism and Virtual Functions
#include <iostream>
using std::cout;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class Rectangle: public Polygon {
public:
virtual int area()
{ return width*height; }
};
class Triangle: public Polygon {
public:
virtual int area()
{ return width*height/2; }
};
int main () {
Rectangle rect;
Triangle tri;
Polygon* ppoly1 = ▭
Polygon* ppoly2 = &tri;
ppoly1->set_values (4,9);
ppoly2->set_values (4,9);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
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).
// Overloading Increment Operator
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
class Rational
{
public:
Rational(int n, int d): numerator(n), denominator(d) {};
Rational& operator++() {
++numerator;
return *this;
}
Rational operator++(int n) {
Rational temp(numerator, denominator);
denominator++;
return temp;
}
void show() { cout << numerator << '/' << denominator << '\t'; }
int numerator;
int denominator;
};
int main()
{
Rational a(1, 2);
Rational b(3, 4);
(++a).show();
b++.show();
a.show();
b.show();
return 0;
}