C++基礎知識梳理--C++的6個預設函數

來源:互聯網
上載者:User

標籤:

C++有六個預設函數:分別是

1、default建構函式;

2、預設拷貝建構函式;

3、預設解構函式;

4、賦值運算子;

5、取值運算子;

6、取值運算子const;

例:

Person.h#ifndef PERSON_H#define PERSON_H#include <iostream>#include <string>using namespace std;class Person{public:    Person();   // deafault建構函式;    Person(const Person&);  // 預設拷貝建構函式    ~Person();  // 解構函式    Person& operator = (const Person &);    // 賦值運算子    Person *operator &(); // 取值運算子    const Person *operator &() const; // 取值運算子constpublic:    string getName() { return sName; }    string getCode() { return sCode; }    void setName(string name);    void setCode(string code);    void printInfo();private:    string sName;    string sCode;};#endif // PERSON_H

 

Person.cpp#include "Person.h"Person::Person(){    cout << "運行:default建構函式;" << endl;}Person::Person(const Person &src){    cout << "運行:copy建構函式;" << endl;    sName = src.sName;    sCode = src.sCode;}Person::~Person(){    cout << "運行:解構函式;" << endl;}Person &Person::operator =(const Person &src){    cout << "運行:賦值運算子;" << endl;    sName = src.sName;    sCode = src.sCode;    return *this;}Person *Person::operator &(){    cout << "運行:取址運算子;" << endl;    return this;}const Person *Person::operator &() const{    cout << "運行:取址運算子const;" << endl;    return this;}void Person::setName(string name){    sName = name;}void Person::setCode(string code){    sCode = code;}void Person::printInfo(){    cout << "Name : " << sName << endl;    cout << "Code : " << sCode << endl << endl;}
main.cpp#include <iostream>#include "Person.h"using namespace std;int main(){    // 建立a    Person a;    a.setName("李明");    a.setCode("0101");    // 建立b    Person b(a);    b.setCode("0102");    // 建立c    Person c;    c = b;    c.setCode("0103");    // 建立d    Person *d;    d = &a;    d->setCode("0104");    // 輸出    a.printInfo();    b.printInfo();    c.printInfo();    d->printInfo();    return 0;}

 

輸出結果:

 

 

只聲明一個空類而不去使用時,編譯器會預設產生:

1、default建構函式;  2、預設拷貝建構函式;  3、預設解構函式;  4、賦值運算子;

 

 

建構函式:

建構函式用於建立對象,對象被建立時,編譯系統對對象分配記憶體空間,並自動調用建構函式。

建構函式啟動並執行過程是:

1、系統建立記憶體空間,調用建構函式;

2、初始變數表;

3、函數體部分運行;

解構函式:

在對象析構時被掉用,用於析構對象,釋放記憶體;

copy建構函式:

 

C++基礎知識梳理--C++的6個預設函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.