內(nèi)聯(lián)函數(shù)直接在頭文件中定義。
string.h
#ifndef __MYSTRING_
#define __MYSTRING_
#include
class String
{
public:?
? ? ? ? ? string(const char* str = 0){}
? ? ? ? ? String(const String* s) {}
? ? ? ? ? ?String& operator=(const String& s){}
? ? ? ? ? ? ~String(){}
char* Data()const {return this->data;}private:char* data;};
ostream& operator<<(ostream& os,const String& s)
{
? ? ? ? ? ?return os << s.Date();
}
#endif
//Big Three 三巨頭:指的是 帶指針的類的拷貝構(gòu)造函數(shù)恤磷、拷貝賦值函數(shù)条获、析構(gòu)函數(shù)钞艇。
淺拷貝:按值拷貝。
深拷貝:按內(nèi)容拷貝驯遇,適用于有指針成員的類谱仪。
自賦值:a = a;?
內(nèi)存管理:棧掸读、堆
棧:CPU自動(dòng)管理串远。不需要程序員來(lái)管。
堆:操作系統(tǒng)的資源儿惫,需要程序員自己申請(qǐng)和自己釋放澡罚。不釋放會(huì)造成內(nèi)存泄漏。
函數(shù)調(diào)用棧:用來(lái)防止函數(shù)內(nèi)部局部變量肾请、函數(shù)入口參數(shù)以及函數(shù)返回值等留搔。
//global?
Complex c3(3,4);? data段。
void function()
{
? ? ? ? Complex c1(2,3);
? ? ? ? ?Complex* p = new Complex(1,2);//
? ? ? ? ?delete p;
? ? ? ? ? static Complex c4(3,5);
}
C++ 運(yùn)算符 new的工作過(guò)程:先分配內(nèi)存铛铁,然后調(diào)用 構(gòu)造函數(shù)隔显。
Complex* pc = new Complex(1,2);
new 《=等價(jià)于=》?
? ? ? ?Complex* pc;
? ? ? ?void * mem = operator new (sizeof(Complex));//內(nèi)部調(diào)用malloc();
? ? ? ?pc = static_cast(mem);pc->Complex::Complex(1,2);
? ? ? ? String* ps = new String("hello");
delete <<=等價(jià)于=>>
? ? ? ? 1、先析構(gòu)饵逐。String::~String(ps);
? ? ? ? ?2括眠、再釋放內(nèi)存。 operator delete(ps);
?delete[] 必須和 new []對(duì)應(yīng)? ? ? 不然會(huì)造成內(nèi)存泄漏.
delete? 和 new? 對(duì)應(yīng)倍权。
static:類的靜態(tài)數(shù)據(jù)成員掷豺,是類的所有對(duì)象共享的,它存儲(chǔ)在 內(nèi)存的靜態(tài)數(shù)據(jù)區(qū)域薄声,某一個(gè)類的對(duì)象修改了static數(shù)據(jù)成員当船,所有的類的其他對(duì)象都可見(jiàn)這種修改。
類的靜態(tài)數(shù)據(jù)成員初始化只能在類外進(jìn)行默辨,如: int ClassName::m_static_data = 9;這個(gè)類似于全局變量的初始化德频。
類的靜態(tài)函數(shù)沒(méi)有this指針,因此只能訪問(wèn)類的靜態(tài)函數(shù)或靜態(tài)數(shù)據(jù)成員缩幸。
靜態(tài)函數(shù)可以通過(guò)對(duì)象.fun_static()來(lái)訪問(wèn)壹置〉凳澹或者直接用類名::fun_static()調(diào)用。
單實(shí)例類---設(shè)計(jì)模式
模板類:
template Ttemplateclass B
? ? ? {?
?? ? }
模板就是實(shí)現(xiàn)代碼重用機(jī)制的一種工具蒸绩,它可以實(shí)現(xiàn)類型參數(shù)化衙四,即把類型定義為參數(shù),從而實(shí)現(xiàn)了真正的代碼可重用性患亿。
模版可以分為兩類传蹈,一個(gè)是函數(shù)模版,另外一個(gè)是類模版步藕。
模板函數(shù):引數(shù)推導(dǎo)惦界。
運(yùn)算符重載。
templateT min(T x,T y)
C++標(biāo)準(zhǔn)算法庫(kù):模板函數(shù)咙冗。通用算法庫(kù)沾歪。
命名空間:包裝一下代碼、數(shù)據(jù)雾消;便于隱藏灾搏,防止重名。
object based? 基于類立润, 面向?qū)ο蟆?/p>