淺談C++類(2)–一個簡單的多檔案具體例子

來源:互聯網
上載者:User

上一次講了一些基本的概念,這次分析一個稍微複雜但其實還是很簡單的例子。現看定義:

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,因為標頭檔中最好不要用這個。其實在小程式中倒也無所謂。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.