C++知識總結--類

來源:互聯網
上載者:User

標籤:

1. 類的成員存取控制

類的成員三種訪問類型:public,private,protected(預設為private)

while, 結構體的預設訪問類型為public

 

2.  const成員函數

class A { public:   void func ( ) const;  /* promise not to change invoking object */};void A::func( ) const {  ...}const A a;  /* a is constant object */類的const對象只能調用類的const成員函數

 

3. 操作符重載

操作符左側的對象是調用對象,操作符右側的對象是作為參數被傳遞的對象

class Time {private:    int hours;    int minutes;public:    Time operator+ (const Time &t) const;};
Time Time::operator+(const Time &t) const {  Time sum;  sum.minutes = minutes + t.minutes;  sum.hours = hours + t.hours + sum.minutes / 60;  sum.minutes = sum.minutes % 60;  return sum;}

int main() {
  Time a;
  Time b;
  Time total;

  total = a + b;
}

不能重載的操作符:

sizeof

成員操作符"."

成員指標操作符"*"

"::"

"?:"

typeid

const_cast

static_cast

dynamic_cast

reinterpret_cast

大多數操作符都可以通過成員函數或者非成員函數進行重載,但下面的操作只能重載為成員函數

=   賦值操作符

()   函數叫用作業符

[]  下標操作符

-> 通過指標訪問成員的操作符

 

4. 友元

為啥要友元:舉個栗子

class Time {private:    int hours;    int minutes;public:    Time operator* (double m) const;};這樣重載的*在調用時操作符左側必須是類對象,自然地會改寫為Time operator*(double m, const Time &t);
使用非成員函數可以按照所需的順序獲得運算元,但是非成員函數不能訪問類的私人資料而通過讓函數成為類的友元,可以賦予函數與類的成員函數相同的存取權限。

class Time {private:    int hours;    int minutes;public:    friend Time operator* (double m, const Time &t);};

 /* 在定義時不需要加friend關鍵字 */
Time operator*(double m, const Time &t) {  Time result;  result.minutes = t.hours * m * 60 + t.minutes * 60;  result.hours = result.minutes / 60;  result.minutes = result.minutes % 60;  return result;}

 

重載<<

void operator<<(ostream &os, const Time &t);  /* 不能拼接輸出,cout<<"haha"<<t<<endl; 是不能工作的 */ostream& operator<<(ostream &os, const Time &t);

 

 

 

C++知識總結--類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.