一、引用
int y;
int& r = y;
const int& q = 12;
規(guī)則:
創(chuàng)建時(shí)必須被初始化
一旦初始化指向一個(gè)對(duì)象,就不能再變?yōu)槠渌麑?duì)象引用
不能有NULL應(yīng)用,因?yàn)橐檬歉粋€(gè)合法的存儲(chǔ)單元關(guān)聯(lián)。
指針引用:
如果想改變指針本身,必須傳遞指向指針的指針,可以用指針引用清晰表達(dá)
void f(int**);// pointer to pointer
void f(int*&);// reference to poiner
參數(shù)傳遞時(shí),一般通過(guò)常量引用來(lái)傳遞,因?yàn)閭鬟f的中間量都是const的。
二、拷貝構(gòu)造函數(shù)
按值傳遞和按值返回的時(shí)候會(huì)調(diào)用拷貝構(gòu)造函數(shù),并且按位拷貝。從現(xiàn)有對(duì)象創(chuàng)建新對(duì)象。創(chuàng)建新對(duì)象的時(shí)候就應(yīng)該調(diào)用構(gòu)造函數(shù),并且如果類(lèi)里面有指針的話(huà),必須要對(duì)其控制,防止指向同一內(nèi)存塊。
class withCC
{
string id;
public:
withCC(const withCC&){}
};
class woCC
{
string id;
public:
woCC(){}
};
class Composite
{
withCC withcc;
woCC wocc;
public:
Composite(){}
};
int main()
{
Composite c;
Composite c1 = c;//調(diào)用withCC 和woCC的拷貝構(gòu)造函數(shù)
}
所以在編寫(xiě)我們自己的拷貝構(gòu)造函數(shù)的時(shí)候,最好也要調(diào)用成員對(duì)象的拷貝構(gòu)造函數(shù)。
指向成員的指針
class Data
{
public:
int a, b, c;
};
int main()
{
Data d, *dp = &d;
int Data::*pmInt = &Data::a;//pmInt 是一個(gè)指向Data類(lèi)中所有int類(lèi)型的指針,現(xiàn)在初始化為Data類(lèi)中a的地址。
dp->*pmInt = 46;
pmInt = &Data::b;
d.*pmInt = 48;
}
函數(shù)指針:回調(diào)函數(shù)的基礎(chǔ)
class Widget
{
public:
void f(int) const {}
void g(int) const {}
void h(int) const {}
void k(int) const {}
};
int main()
{
Widget w;
Widget* wp = &w;
void(Widget::*pmem)(int) const = &Widget::h;
(w.*pmem)(1);
(wp->*pmem)(2);
}
類(lèi)成員指針
class Widget{
private:
void f(int)const{}
void g(int)const{}
void k(int)const{}
void m(int)const{}
void(Widget::*fptr[4])(int)const;
public:
Widget(){
fptr[0] = &Widget::f;//必須寫(xiě)完整,不能因?yàn)樵陬?lèi)中而用fptr[0] = f;
fptr[1] = &Widget::g;
fptr[2] = &Widget::k;
fptr[3] = &Widget::m;
}
void select(int i, int j)
{
assert(i >0 && i < 4);
(this->*fptr[i])(j);//必須這么寫(xiě),要讓編譯器能判斷,這是一個(gè)類(lèi)成員函數(shù)的指針。
}
總結(jié):引用必須和一個(gè)存儲(chǔ)單元聯(lián)系起來(lái);傳值的時(shí)候會(huì)使用拷貝構(gòu)造函數(shù),為了防止位拷貝,最好自己寫(xiě)拷貝構(gòu)造函數(shù)。為了防止傳值,使拷貝構(gòu)造函數(shù)為私有的,這里有個(gè)例子ostream os,不能這么寫(xiě),必須傳遞引用。
1
posted on 2012-05-31 17:01
Dino-Tech 閱讀(196)
評(píng)論(0) 編輯 收藏 引用