(5%) 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).
// Function Pointers (P.393)
#include <iostream>
int add(int a, int b)
{ return a + b; }
int sub(int a, int b)
{ return a - b; }
int mul(int a, int b)
{ return a * b; }
int divide(int a, int b)
{ return a / b; }
int main()
{
int *f[](int, int) = { add, sub, mul, divide };
for (int i=0; i<4; i+=2)
{
std::cout << f[i](33, 5) << std::endl;
}
return 0;
}
(5%) 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,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
return 0;
}
(5%) 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).
// Recursion
#include <iostream>
using std::cout;
void f(int a[], int i)
{
if (a[i] > 0)
{
f(a, i*2);
f(a, i*2+1);
cout << a[i] << ' ';
}
}
int main()
{
int a[32] = {15, 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 };
f(a, 1);
cout << std::endl;
return 0;
}