(From 九天雁翎)
Person.h
#include <map>
#include <string>
class Person
{
public:
Person(const std::string &,const std::string &);
Person(){};
void print(const std::string &) const; //聲明一個const成員函數輸出
void print();
void input(const std::string &,const std::string &);
private:
std::map<std::string,std::string> aperson;
};
Person.cpp
#include "Person.h"
#include <iostream>
#include <iterator>
#include <algorithm>
Person::Person(const std::string &name,const std::string &adress) //一個構造函數
{
aperson[name] = adress;
}
void Person::print(const std::string &name) const //定義了一個const成員函數,輸出
{
std::map<std::string,std::string>::const_iterator it = aperson.find(name);
//在aperson中查找key name
if(it != aperson.end()) //假如有就輸出
{
std::cout<<it->first<<"'s adress is "<<it->second<<std::endl;
}
else
{
std::cout<<"there is no this person called"<<name<<std::endl;
}
}
void Person::print() //重載一個輸出,沒有參數就輸出所有的值
{
for(std::map<std::string,std::string>::iterator it =aperson.begin(); //遍歷aperson
it != aperson.end();++it)
{
std::cout<<it->first<<" in "<<it->second<<std::endl;
}
}
void Person::input(const std::string &name, const std::string &adress)
//用input管理輸入
{
aperson[name] = adress; //有就改名,沒有就增加一個,利用map下標的特點
}
這個類使用的方法具體可以參考下面,你也可以自己試試:
#include "Person.h"
#include <string>
int main()
{
Person abook("jack","Guanzhou");
abook.input("jim","Beijing");
abook.input("tom","Hunan");
abook.print("jack");
return 0;
}
在這里注意,和以前說的不同的是,類的被分開放在兩個文件中,而且,類中的函數都在類定義外面定義,這里這樣做是因為既然要封裝,那么類的使用者就沒有必要知道第2個文件,知道第一個文件就夠了,只要你詳細說明了每個函數的實際用途,類的使用者可以不關系他的具體實現,節省時間和精力。這是雷同於C中編寫不同的函數的程序員之間也不需要實際了解那個函數具體怎么實現的一樣,C就是這樣實現結構化編程的,而C++就是通過這樣寫類,來實現面向對象編程的。在類外定義類的成員函數,你必須指明,這個函數是某個類的函數,通過符號“::”,在上面的例子中很明顯。另外,所謂的 const成員函數,表示這個函數不能更改類中的數據,在聲明及定義中都必須加上const.public下的東西可以公共訪問,所以被叫做一個類的接口,什么叫接口?就是和外部產生聯系所需要的東西。private下的別人就不需要了解了,叫封裝,也是一種黑盒原理。可以看到,這里有2個接口函數,print(),input();其中print()有一個重載版本。還有1個重載的構造函數。看名字都很好理解。數據中就定義了一個由2個string組成的map。這里把類的定義放在一個單獨的頭文件里面,所以都用了std::而沒有用using namespace std,因為頭文件中最好不要用這個。其實在小程序中倒也無所謂。
