回覆列表
  • 1 # 使用者9923191605008

    class student{private: string name; char gender;public: student(string n,char g):name(n),gender(g){} //初始化列表使屬性一次性賦值完畢,否則需要兩次 friend ostream& operator<<(ostream& cout,student &s); //定義為friend便可擁有訪問private屬性的許可權};

    ostream& operator<<(ostream& cout,student &s){ cout<<s.name<<" "<<s.gender; return cout;}

    在寫主函式

    int main(){ map<string,student> sm; student ts("lishuai","M"); sm[“001”] = ts;//檢索key=”001”的值,如果存在,用ts覆蓋,如果不存在,插入ts for(map<string,student>::iterator it = sm.begin();it!=sm.end();it++) { cout<<(*it).second<<endl;呼叫operaotr<<過載函式列印student物件 } system("pause"); return 0;}

    執行報了一堆錯:後來發現最根本問題是無法找到student()無參建構函式。於是在類中新增建構函式

    student(){}

    後執行正確。結果為

    lishuai M

    說明在插入過程中,如果沒找到物件,就先呼叫無參建構函式。但這隻能構造一個空的物件,那一定還會呼叫賦值函式填寫其屬性,賦值函式是編譯器自動為我們寫的,為了搞清楚這個具體過程,我自己來實現。

    class student

    {

    private:

    string name;

    char gender;

    public:

    student(){cout<<"Default Constructor"<<endl; name="---------";}//給個空名字

    student(string n,char g):name(n),gender(g){cout<<"Constructor:"<<name<<endl;}

    student& operator=(const student& s);

    student(const student& s);

    ~student(){cout<<"Destructor:"<<this->name<<endl;}

    friend ostream& operator<<(ostream& cout,student &s);

    };

    student& student::operator=(const student& s)

    {

    cout<<"Assignment:"<<s.name<<endl;

    this->name = s.name;

    this->gender = s.gender;

    return *this;

    }

    student::student(const student& s)

    {

    static char c="a";

    this->name = s.name+c++; //每呼叫一次,就改變名字

    this->gender = s.gender;

    cout<<"Copy Constructor:"<<this->name<<endl;

    }

    ostream& operator<<(ostream& cout,student &s)

    {

    cout<<s.name<<" "<<s.gender;

    return cout;

    }

    int main()

    {

    map<string,student> sm;

    student ts("lishuai","M");

    cout<<"begin"<<endl;

    sm["001"]=ts;

    cout<<"end"<<endl;

    for(map<string,student>::iterator it = sm.begin();it!=sm.end();it++)

    {

    cout<<(*it).second<<endl;

    }

    system("pause");

    return 0;

    }

    執行結果:

    Constructor:lishuai

    begin

    Default Constructor //構造空物件1

    Copy Constructor:---------a //構造空物件2

    Copy Constructor:---------ab //構造空物件3

    Destructor:---------a //析構空物件2

    Destructor:--------- //析構空物件1

    Assignment:lishuai //給物件3賦值

    end

    lishuai M

    可以看到,在插入的過程中,首先呼叫1次無參建構函式,然後呼叫2次複製建構函式依次複製前一個建立的物件,再呼叫兩次解構函式析構頭2個空物件,最後呼叫一次賦值函式。

  • 中秋節和大豐收的關聯?
  • 如何養狗比較好?