[C++]实验八:学习类的聚集使用方法

//Dictionary.cpp

#include "Dictionary.h"

void Dictionary::AddWord(string word, string meaning)
{
 if (_full>=100) cout << "达到最大存储量";
 else
 {
  words[_full].edit(word);
  words[_full].addNewMeanings(meaning);
  _full++;
 }
}

void Dictionary::DetDef (string word)
{
 for (int i=0; i < _full ;i++)
  if (words[i].isword(word))
  {
   words[i].showWordAndMeanings();
  }
}

//Dictionary.h

#include "word.h"
#include <iostream>
#include <string>
using namespace std;
class Dictionary {
public:
 Dictionary ():_full(0){};
 ~Dictionary (){
  cout << "析构字典" << endl;
 }
 void FindWord(string);
 void AddWord(string,string);
 void DetDef(string);
 void Print();
private:
 int _full;
 Word words[100];
};

 

//word.cpp

#include "word.h"
#include <iostream>
#include <vector>
using namespace std;

Word::Word (const Word &other) //复制构造函数
{
 _word = other._word;
 _meaningNum = other._meaningNum;
 for ( int i=0; i< 10; i++)
 _meaning[i] = other._meaning[i];
}

void Word::addNewMeanings (string meanings)
{
 if ( _meaningNum >= 10) cout << "达到最大词义数!";
 else
  _meaning[_meaningNum++] = meanings;
}

void Word::edit(string newWord)
{
 _word = newWord;
}

void Word::showWordAndMeanings()
{
 cout << "单词" << _word << "的意思有:" << endl;
 for ( int i=0; i< _meaningNum;i++)
  cout << "第"<<i+1<<"种: " << _meaning[i] <<endl;
 cout << "/n";
}

//word.h

#include <iostream>
#include <string>
using namespace std;
class Word{
public:
    Word():_meaningNum(0){}; //默认构造函数
 Word (const Word &other); //复制构造函数
 Word ( string word ,string meaning ):_word(word),_meaningNum(1) {_meaning[0]=meaning;}; //含参构造函数
 //~Word(){ cout << "析构" << _word <<endl ;_meaningNum=0;}; //析构函数
 int isword (string word) {
  if (word==_word)
   return 1;
  else return 0;
 }
 void addNewMeanings (string meanings); //添加词义
 void showWordAndMeanings(); //show词义和单词
 void edit(string newWord); //修改单词
private:
 string _word;
 int _meaningNum;
 string _meaning[10];
};

//main.cpp

/*
1. 在实验7题2单词类的基础上建立一个词典。
词典应由一个一个单词组成,故Dictionary类中包含了Word类的对象数组
(默认时可存放100个单词及其含义)。在Dictionary类中应含有下列成员函数:
- 构造函数
- 析构函数
- 查找单词 FindWord
- 增加单词 AddWord
- 取得单词的全体解释 DetDef
- 输出单词内容 Print  等
在主程序中对所编写的Dictionary类的进行使用测试。
*/

#include "Dictionary.h"
#include <iostream>
using namespace std;

void main()
{
 Dictionary Dic;
 Dic.AddWord("good","好");
 Dic.AddWord("bad","坏");
 Dic.DetDef("bad");
}

展开阅读全文

没有更多推荐了,返回首页