對于c++中常量成員函數,返回常量引用,const_cast的總結
常量成員函數:
先看這個例子
bool Sales_item::same_isbn(const Sales_item &rhs) const
{ return (isbn rhs.isbn);}
藍色的const用于修飾顯示傳入的形參rhs,而對于類的成員則有隱式的,而外的this指針作為形參傳入,而紅色部分的const正是修飾這部分參數this;
const 成員函數的引入
現在,可以理解跟在Sales_item 成員函數聲明的形參表后面的const 所起的作用了: const改變了隱含的this 形參的類型。在調用total.same_isbn(trans) 時,隱含的this 形參將是一個指向total 對象的const Sales_item*類型的指針。就像如下編寫same_isbn 的函數體一樣:
/ / pseudo-code illustration of how the implicit this pointer is used
/ / This code is illegal: We may not explicitly define the this pointer ourselves
/ / Note that this is a pointer to const because same_isbn is a const member
bool Sales_item::same_isbn(const Sales item *const this ,const Sales_item &rhs) const


{ return (this->isbn rhs.isbn);}
用這種方式使用const 的函數稱為常量成員函數(const member function) 。由于this 是指向const 對象的指針,const 成員函數不能修改調用該函數的對象。因此,函數avg-price
和函數sarne isbn 只能讀取而不能修改調用它們的對象的數據成員。
NOTE:
const對象指向const的指針或引用只能用于調用其const成員函數如果嘗試用它們來調用非const 成員函數,則是錯誤的。
返回常量引用:
在看一個例子:
1
mycls const& returntest()//定義返回值為一個常量引用
2

{
3
mycls my1(3);
4
cout<<"a in the func is"<<&my1<<endl;
5
return my1;
6
}
7
int _tmain(int argc, _TCHAR* argv[])
8

{
9
//測試返回引用類型
10
mycls const&str = returntest();//使用cont&接受返回值
11
//str.m_q=12;//編譯報錯,不可以修改const類型
12
mycls &str1=const_cast<mycls&>(str);//去掉const屬性,以便修改
13
str1.m_q=12;
14
cout<<"&b="<<&str<<endl;
15
cout<<"&b="<<&str1<<endl;
16
system("pause");
17
return 0;
18
}
mycls const& returntest()//定義返回值為一個常量引用2


{3
mycls my1(3);4
cout<<"a in the func is"<<&my1<<endl;5
return my1;6
}7
int _tmain(int argc, _TCHAR* argv[])8


{9
//測試返回引用類型10
mycls const&str = returntest();//使用cont&接受返回值11
//str.m_q=12;//編譯報錯,不可以修改const類型12
mycls &str1=const_cast<mycls&>(str);//去掉const屬性,以便修改13
str1.m_q=12;14
cout<<"&b="<<&str<<endl;15
cout<<"&b="<<&str1<<endl;16
system("pause");17
return 0; 18
}以上mycls是我自己定義的一個類,聲明如下
1
class mycls
2

{
3
public:
4
mycls(int a);
5
char a[100000];
6
//~mycls(void);
7
int m_q;
8
template <class T> inline int compare(const T &a,const T &b)
9
{
10
if(a == b)
11
return 0;
12
else if(a > b)
13
return 1;
14
else if(a<b)
15
return -1;
16
return 0;
17
}
18
mycls& operator+(mycls a);
19
virtual int dosomething(int a);
20
virtual void doanotherthing(void);
21
};
22
通過代碼注釋,我想這不難理解,用一個引用類型的返回值最大好處就是可以避免內存拷貝,注意到我的類中有一個長度為100000的char數組,我想頻繁拷貝這個數組對于一下性能較低的機器還是很耗時的,這時我們返回const &類型,避免了文件的拷貝,從輸出也可以看到,returntest函數內的對象地址與main函數內所返回的引用對象地址完全一致。
class mycls2


{3
public:4
mycls(int a);5
char a[100000];6
//~mycls(void);7
int m_q;8
template <class T> inline int compare(const T &a,const T &b)9

{10
if(a == b)11
return 0;12
else if(a > b)13
return 1;14
else if(a<b)15
return -1;16
return 0;17
}18
mycls& operator+(mycls a);19
virtual int dosomething(int a);20
virtual void doanotherthing(void);21
};22

posted on 2008-12-04 17:08 pear_li 閱讀(3488) 評論(4) 編輯 收藏 引用 所屬分類: C++
