C 宣告之CV限定符

2022-08-23 14:18:11 字數 2000 閱讀 5027

目錄

1.const

1.1 const obj 如果呼叫 non-const member fun會編譯出錯

經典錯誤

1.2 例子:std裡的操作符過載

1.3 例子:《cpp primer》15節 -基類的定義

class complex

complex& operator += (const complex&);

complex& operator -= (const complex&);

complex& operator *= (const complex&);

complex& operator /= (const complex&);

double real () const

double imag () const

private:

double re, im;

friend complex& __doapl (complex *, const complex&);

friend complex& __doami (complex *, const complex&);

friend complex& __doaml (complex *, const complex&);

};

只有member fun後面可以用 const定義。成員變數後面不可以寫const,寫在前面。

如果定義時沒有寫成void print() const{}; 就會報錯。因為str是const-obj,不能用non-const member fun呼叫。

來自 template class basic_string的定義。string類的operator。

reference operator(size_type _off)

const_reference operator(size_type _off) const

class quote 

#endif // !defined(in_class_inits) && defined(default_fcns)

//初始化建構函式

quote(const string &book,double sales_price):

bookno(book),price(sales_price)

//虛析構函式,動態繫結

#ifdef default_fcns

virtual ~quote() = default;

#else

virtual ~quote()

#endif // default_fcns

//const fun。 因為bookno被期望是const obj,所以只能被const fun呼叫,必須定義為const fun,否則報錯。

string isbn() const

//虛函式。將在派生類中重寫,根據書的數量,採取不同的折扣演算法。

//因為price(定價)也是const obj,不會被改。所以定義為const fun。

virtual double net_price(size_t n) const

//虛函式返回動態分配的自身副本

private:

const string bookno;//書號,被期望是const obj

protected:

#ifndef in_class_inits

const double price = 0.0;

#else

const double price;

#endif // !in_class_inits

};

C 說明符和CV限定符

1.下面是儲存所說明符 2.下面就是cv限定符 volatile 關鍵字volatile表明,即使程式 沒有對記憶體單元進行修改,其值也可能發生變化。例如,可以將指標指向某個硬體位置,其中包含了來自串列埠的時間和資訊。在這種情況下,硬體 而不是程式 可能修改其中的內容。或者兩個程式可能互相影響,共享...

C 之const限定符

const的特點 用const加以限定的變數,無法改變。由於const物件定義之後就無法改變,所以必須對其進行初始化。const物件的常量特徵僅在嘗試改變它的時候表現出來,其他時候和變數無異。const初始化 const int bufsize 512 bufsize無法再改變const物件通常只在...

c 儲存說明符以及cv限定符總結

c 中的儲存說明符種類如下 cv限定符有 下面詳細說一下功能 auto 在c 11之前用來表示變數是一種自動型的變數,其儲存的生命週期為乙個函式或者 塊裡,若不顯式定義,預設為自動儲存變數。而在c 11之後,auto被用作自動判別資料型別。例如以下 c 11標準及以上 int a 1,b 2 aut...