第五章习题
7、写出下列程序的运行结果。
#include <iostream>
using namespace std;
class A
{
public:
A(int i) : x(i) {}
A() { x = 0; }
friend A operator++(A a);
friend A operator--(A &a);
void print();
private:
int x;
};
A operator++(A a)
{
++a.x;
return a;
}
A operator--(A &a)
{
--a.x;
return a;
}
void A::print() { cout << x << endl; }
int main()
{
A a(7);
++a;
a.print();
--a;
a.print();
return 0;
}
- 写出下列程序的运行结果。
#include <iostream>
using namespace std;
class Words
{
public:
Words(char *s)
{
str = new char[strlen(s) + 1];
strcpy(str, s);
len = strlen(s);
}
void disp();
char operator[](int n);
private:
int len;
char *str;
};
char Words::operator[](int n)
{
if (n < 0 || n > len - 1)
{
cout <<”数组下标越界!\n”;
return ‘ ‘;
else return *(str + n);
}
void Words::disp() { cout << str << endl; }
int main()
{
Words word(“This is C++ book.”);
word.disp();
cout <<”第1个字符:”;
cout << word[0] << endl;
cout <<”第16个字符:”;
cout << word[15] << endl;
cout <<”第26个字符:”;
cout << word[25] << endl;
return 0;
}
9. 写出下列程序的运行结果。
#include <iostream>
using namespace std;
class Length
{
int meter;
public:
Length(int m) { meter = m; }
operator double() { return (1.0 * meter / 1000); }
};
int main()
{
Length a(1500);
double m = float(a);
cout <<”m =” << m <<”千米”<< endl;
return 0;
}