C Prime 第14章後23題

2021-10-07 18:35:45 字數 3357 閱讀 5442

智慧型指標或內建型別,可以自己管理自己擁有的資源,於是使用編譯器合成的拷貝控制函式就滿足要求了.

classx;

private

: strblobptr* ptr;

};

過載的函式呼叫運算子最少接受0個物件,最多接受無限個物件.

#pragma once

#include

using

namespace std;

//圖省事

class

test

;private:}

;

class

readstring

private

: string mem;

istream& is = cin;

};

int

main()

int

main()

;for

(auto x : data)

cout << x <<

" ";

cout << endl;

int n;

while

(cin >> n)

return0;

}

class

test

bool

operator()

(const string& s)

private

:int threshold =0;

};intmain()

;int i =0;

while

(++i <=10)

}}test t;

for(

int i =

1; i <=10;

++i)

cout <<

"長度為"

<"的單詞有: "

<< data[i]

<<

"個\n"

; cout << endl;

return0;

}

從data[1]累加到data[9]

lambda可以內嵌在函式中,直接瀏覽函式定義,了解函式功能.

沒有呼叫函式的開銷.

需要實現的功能太為複雜時,使用類.

count_if

(data.

begin()

, data.

end(),

bind

(greater<

int>()

,2))

;find_if

(svec.

begin()

, svec.

end(),

bind

(not_equal_to()

,"pooh"))

;transform

(data.

begin()

, data.

end(

),data.

begin()

,bind

(multiplies<

int>()

,2))

;

for_each

(data.

begin()

, data.

end(),

,bind

(modulus<

int>()

, _1)

);

int

add(

int i,

int j)

auto mod =

(int i,

int j)

;struct divide };

intmain()

);//普通函式,函式指標

binops.

insert()

;//命名的lambda表示式

binops.

insert()

;//使用者定義的函式物件

binops.

insert(}

);//匿名的lambda表示式

binops.

insert()

;//標準庫定義的函式物件

cout << binops[

"+"](1

,3)<< endl;

cout << binops[

"-"](1

,3)<< endl;

cout << binops[

"*"](1

,3)<< endl;

cout << binops[

"/"](1

,3)<< endl;

cout << binops[

"%"](1

,3)<< endl;

return0;

}

explicit

operator

string()

const

explicit

operator

double()

const

應該宣告型別裝換運算子,便於轉換.

應該宣告成explicit.避免隱式轉換釀成不可挽回的巨大悲劇.

operator const int() //將類轉換成乙個整型常量值,轉換的過程中可以更改類物件

operator int() const //將類物件轉換成乙個普通int值,轉換的過程中不可更改類物件

不需要轉換

explicit

operator

bool()

const

ex1 會用到double() float()均有可能,二義性呼叫

ex2 會用到float(),精準匹配.

void cal(int)版本,標準轉換優於類的自定義轉換.

ld = si + ld;

內建版本的+,但是不確定使用哪乙個.si->int,ld->float 或者double 二義性.

ld = ld + si;

成員函式版本.

不合法的.

可以這樣:3.14轉換為int型的3,然後3->smalint,調用友元版本的

operator+(const smallint&,const smallint&)

也可以這樣:si轉換成int,呼叫內建的int+double.二義性了

必須顯示轉換,即

explicit operator int()const

C Prime 第14章 前30題

過載運算子與內建運算子 區別 1 某些運算物件的求值規則無法在過載運算子中儲存下來.比如 和 的短路求值特性被捨棄.2 過載運算子必須要求至少有乙個成員是class型別 相同 1 一般來說,優先順序,結合律和運算元的數目是一致的.2 一般來說,表達的邏輯是相同的.friend std istream...

C Prime14章學習筆記

過載的運算子是具有特殊名字的函式,它由關鍵字 operator與後面定義的符號組成,過載函式包含返回型別,引數列表以及函式體。過載運算子的引數數量與該運算子的作用的運算物件數量一樣多。如果乙個運算子函式是成員函式,則其第乙個運算物件繫結到this指標上。注意 對於乙個運算子函式來說,它或者是類的成員...

C Prime 第六章 後36題

返回對區域性變數的引用無效.常量如果是在函式中,那麼其實它也是區域性的,同上.合法滴,將指定陣列元素修改為0 10.include include using namespace std void print vectorvi,int n int main print vi,0 return 0 需...