1.实现要求
建立一个字典类Dict,以支持单词定义对,为其设计适当的成员函数,并重载下标操作符,以支持如下操作。
d["dog"] = "a kind of animal"
该操作表明:d对象的第dog元素是a kind of animal
这种下标不是整数的数组就是关联式数组
2.测试程序
int main(){
Dict d;//创建一个字典类对象
d["residual fm"]="incidential fm";
d["pixel"]="in a daffy state";
cout<<"\n\ndump\n"<<d;
d["pixel"]="picture element";//改变其中一个定义
cout<<"\n\ndump\n"<<d;
cout<<"\n\nlookup\n\n"<<d;
cout<<d["residual fm"]<<'\n';
cout<<d["pixie"]<<'\n';
cout<<d["pixel"]<<'\n';
return 0;
}
3.关联式数组的实现
设计一个辅助类Entry,用来存储单词,单词的意义和一个有效标记。有效标记表示当前的Entry对象是否存储了有效的单词和意义。
Entry拥有如下成员函数:
1.默认构造函数,该函数将有效标记初始化为false
2.用来添加单词及其定义的成员函数
3.用来测试单词是否匹配的成员函数
4.获取有效标记的成员函数
5.赋值操作符重载函数,将一个字符串(string或c风格)作为单词意义赋给Entry对象
6.重载操作符<<,以输出单词及意义,将其作为Entry的friend函数
class Entry{
public:
Entry(){flag=false;}
void add(const string&,const string&);
bool match(const string& const);
void operator=(const string&);
void operator=(const char*);//重载=
bool valid() const{return flag;}
friend ostream& oparetor<<(ostream&,const Entry&);
private:
string word;
string def;
bool flag;
};
void Entry::operator=(const string& str){
def= str;
flag = true;
}
void Entry::operator=(const char* str){
def= str;
flag = true;
}
ostream& operatr<<(ostream& out,const Entry&e){
out<<e.word<<"defined as:'"<<e.def;
return out;
}
void Entry::addd(const string&w,const string&d){
word = w;
def=d;
}
bool Entry::match(const string& key) const{
return key==word;
}
创建Dict类
1.Dict类只有一个数据成员,即类型为Entry的数组,用来存储单词及意义。
2.Dict类重载了下标操作符
3.Dict声明了一个enum常量MaxEntries,用来定义Entry数组
4.采用friend方式为Dict类设计了一个顶层的<<操作符重载函数,用来输出字典中所有元素。
class Dict{
public:
enum{MaxEntries=100};
friend ostream& operator<<(ostream&,const Dict&);
Entry& operator[](const string&);
Entry& operator[](const char*);//重载下标操作符
private:
Entry entries[MaxEntries +1];//数据成员,类型为Entry的数组
};
Entry& Dict::operator[](const string& k){
for(int i = 0; i<MaxEntries && entries[i].valid();i++)
if(entries[i].match(k))
return entries[i];
string not_found="*** not in the dictionary";
entries[i].add(k, not_found);
return entries[i];
}
Entry& Dict::operator[](const char* k){
string s = k;
return operator[](s);
}
ostream& operator<<(ostream& out, const Dict&d){
for(int i = 0; i<MaxEntries;i++)
if(d.entries[i].valid())
out<<d.entries[i]<<'\n';
return out;
}