標籤:
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個預設函數