34-复习题
12.9 复习题
1.假设String类有如下私有成员:
class String
{
private:
char * str; // points to string allocated by new
int len; // holds length of string
//...
};
a.下述默认构造函数有什么问题?
String::String() {}
b.下述构造函数有什么问题?
String::String(const char * s)
{
str = s;
len = strlen(s);
}
c.下述构造函数有什么问题?
String::String(const char * s)
{
strcpy(str, s);
len = strlen(s);
}
2.如果您定义了一个类,其指针成员是使用new初始化的,请指出可能出现的3个问题以及如何纠正这些问题。
3.如果没有显式提供类方法,编译器将自动生成哪些类方法?请描述这些隐式生成的函数的行为。
4.找出并改正下述类声明中的错误:
class nifty
{
// data
char personality[];
int talents;
// methods
nifty();
nifty(char * s);
ostream & operator<<(ostream & os, nifty & n);
}
nifty:nifty()
{
personality = NULL;
talents = 0;
}
nifty:nifty(char * s)
{
personality = new char [strlen(s)];
personality = s;
talents = 0;
}
ostream & nifty:operator<<(ostream & os, nifty & n)
{
os << n;
}
5.对于下面的类声明:
class Golfer
{
private:
char * fullname; // points to string containing golfer's name
int games; // holds number of golf games played
int * scores; // points to first element of array of golf scores
public:
Golfer();
Golfer(const char * name, int g= 0);
// creates empty dynamic array of g elements if g > 0
Golfer(const Golfer & g);
~Golfer();
};
a.下列各条语句将调用哪些类方法?
Golfer nancy; // #1
Golfer lulu(“Little Lulu”); // #2
Golfer roy(“Roy Hobbs”, 12); // #3
Golfer * par = new Golfer; // #4
Golfer next = lulu; // #5
Golfer hazzard = “Weed Thwacker”; // #6
*par = nancy; // #7
nancy = “Nancy Putter”; // #8
b.很明显,类需要有另外几个方法才能更有用,但是类需要那些方法才能防止数据被损坏呢?