const成員函式

2021-06-05 00:19:43 字數 1300 閱讀 6782

**:prime c++

在類sales_item中,same_isbn函式定義如下: 

bool sales_item::same_isbn(const sales_item &rhs) const 

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

用這種方式使用 const 的函式稱為常量

成員函式。由於this 是指向const 物件的指標,const 成員函式不能修改呼叫該函式的物件。因此,函式 same_isbn 只能讀取而不能修改呼叫它們的物件的資料成員。

class screen 

const screen& display(std::ostream &os) const

private:

// single function to do the work of displaying a screen,

// will be called by the display operations

void do_display(std::ostream &os) const

// as before

};

在函式const screen& display(std::ostream &os) const中,由於this指標的型別為const sales_item *const 所以,return *this時,函式的返回值型別必須為const screen& .

const成員函式

我們知道,在c 中,若乙個變數宣告為const型別,則試圖修改該變數的值的操作都被視編譯錯誤。例如,cpp view plain copy const char blank blank n 錯誤 物件導向程式設計中,為了體現封裝性,通常不允許直接修改類物件的資料成員。若要修改類物件,應呼叫公有成員函...

const成員函式

一.關於const成員函式的呼叫 const物件只能呼叫const成員函式 cpp view plain copy include using namespace std class a void fun intmain 輸出 const 成員函式 但是如果把第以1個fun注釋掉就會出錯 error...

const成員函式

在c 中,若乙個變數宣告為const型別,則試圖修改該變數的值的操作都被視編譯錯誤.例如 const int a 1 a 2 錯誤 c 的const類成員函式 物件導向程式設計中,為了體現封裝性,通常不允許直接修改類物件的資料成員。若要修改類物件,應呼叫公有成員函式來完成。為了保證const物件的常...