- (10%) Determine whether the following code is correct or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
/* Destructor */
#include <iostream>
#include <string>
using std::cout;
using std::string;
class Object
{
public:
Object(string s): name(s)
{ cout << name << "\tconstructed.\n"; }
~Object()
{ cout << name << "\tdestroyed.\n"; }
private:
string name;
};
void f(string s)
{ Object a(s); }
int main()
{
Object a("Alpha");
f("Foxtro");
Object b("Bravo");
return 0;
}
- (10%) Determine whether the following code is correct or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
/* cascaded function calls (P.468) */
#include <iostream>
class Rational
{
public:
Rational(int n, int d): numerator(n), denominator(d) {};
Rational setNumerator(int i) { numerator = i; return *this; }
Rational setDenominator(int i) { denominator = i; return *this; }
void print() { std::cout << numerator << '/' << denominator << std::endl; }
int numerator;
int denominator;
};
int main()
{
Rational a(5, 3);
a.print();
a.setNumerator(4).setDenominator(9);
a.print();
return 0;
}
- (10%) Determine whether the following code is correct or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
/* const member function */
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
class Object
{
public:
Object(string s): name(s) {}
const print() { cout << "const " << name << endl; }
private:
string name;
};
int main()
{
const Object a("Alpha");
a.print();
return 0;
}