C 類操作符過載筆記

2021-07-05 06:32:02 字數 2496 閱讀 6381

不能改變操作符優先順序

不能改變操作符的結合性

不能改變操作符所需要的運算元

不能建立新的操作符

對於二元操作符過載,如果操作符左邊是類 那麼就在該類內部成員函式過載操作符即可

如果操作符左邊不是類,而是乙個常量,那麼就必須在類的外部定義乙個操作符過載函式

有乙個最基本條件  一定有乙個一元是乙個自定義的c++類

如果兩個都是基本資料型別那麼是非法的

//操作符過載

mystring

operator

=(const

mystring&it

)

mystring str1;

mystring str2;

str2 = str1;  //這裡就是一次操作符過載

str2.operator = (str1);  //這是完整版

操作符過載多個 寫在類外面 不能用this  所以最好做上友元

mystring

operator

+(const

char

*str

,const

mystring&it

);

sprintf

(buf

,"%s%s"

,str,it

.s);

strcpy

(str1.s

,buf

);

return

str1

;

};

mystring

str3

;

str3

="aaaa"

+str1

; //可以實現從前面過載 並且過載2個值

過載 == 

bool operator ==(const mystring &it)

二元過載 寫在類外面

friend bool operator ==(const char *str, const mystring &it);  //先做個友元

bool operator ==(const char *str, const mystring &it) ;

「aa」 == str1;

++ 和 --操作符有點特別

str++  和普通過載一樣 但是引數必須是固定的

void operator ++(int i)

++str  必須寫在類外面 通過友元訪問類屬性

friend void operator ++(mystring &it);

void operator ++(mystring &it)

}過載 new  和 delete  必須是成員函式 不能在外面過載

delete 必須返回 void

new 引數必須是 size_t

過載new 必須和 operator有乙個空格 而且引數必須是 size_t 型別的乙個引數

void  * operator new(size_t size)

如果你過載了 new 那麼必須過載delete   delete引數必須是個無型別的指標

void operator delete(void *obj)

過載 new 和 delete  函式引數也是必須按照格式來寫

過載new 會多4個位元組 是讓他刪除的時候能正常的刪除掉

void * operator new(size_t size)

void operator delete(void *obj)

過載 char operator(int index)

過載()

void operator ()(const char *a) 

強制轉換

c++不但允許過載運算操作符,還可以過載強制型別轉換操作符,不過強制型別轉換必須是c++基本資料型別之一,如int,float,char *等,強制型別轉換注意以下幾點:

1、定義函式時不允許有引數,不允許有返回型別,但函式必須返回所需型別的值

2、過載函式只可以是類成員函式,不可以為非類成員函式

類強制轉換成整數

operator int()

實現起來是這樣的

mystring s1;

s1("11111");

int i = (int)s1;

cout << i << endl;  //轉成11111了

可以過載的操作符

+ - * / % ^ & | ~

! = < > += -= *= /= %

^= &= |= << >> >>= <<= == !=

<= >= && || ++ -- ->* 『 ->

() new delete new delete

不能過載的算符

. :: .* ?: sizeof

C 筆記,過載new , delete 操作符

1.簡述 1 自定義過載全域性的new 和 delete,在使用new新增物件和delete物件時,會呼叫自定義全域性的new和delete操作,c 內部類也 如char,int等 不例外,同樣會呼叫自定義的new和delete。2 也可以定義作用域為當前類的new和delete,即像在類中過載其他...

c 操作符過載 學習筆記

1.過載的限制 1 過載後的操作符必須至少有乙個運算元是使用者自定義的型別,這可以防止使用者把標準操作符給過載。比如 t operator double a,double b error 2 不能違反原來操作符的句法規則。3 不能定義新的操作符,否則那就不叫過載了。4 不能過載下面的操作符 size...

C 操作符過載

1.作為成員過載 class myclass public myclass operator const myclass d cons friend myclass operator const myclass a1,const myclass a2 關於返回值型別的討論 呼叫者堆疊裡返回乙個物件效...