複製鏈接
請複製以下鏈接發送給好友

Operator

(計算機關鍵字)

鎖定
operator是C#、C++和pascal的關鍵字,它和運算符一起使用,表示一個運算符函數,理解時應將operator=整體上視為一個函數名。
外文名
Operator
用    法
重載運算符
表    示
一個運算符函數

目錄

Operator關鍵字

這是C++和pascal擴展運算符功能的方法,雖然樣子古怪,但也可以理解:一方面要使運算符的使用方法與其原來一致,另一方面擴展其功能只能通過函數的方式(c++中,“功能”都是由函數實現的)。
使用operator可以賦予原本的運算符新的功能。
如,在比較兩個結構體的大小時,顯然不能直接使用小於號;而這時使用operator可以重載
號,就可以按想要的規則(如:按某一元素的值)來確定大小關係;重載後就可以直接使用小於號來比較。
這是通過重載
實現矩陣乘法的代碼:
MTX operator * (const MTX &mtx1,const MTX &mtx2){
	MTX ans;
	ans.x=mtx1.x,ans.y=mtx2.y;
	for(int i=1;i<=mtx1.x;i++)
		for(int j=1;j<=mtx2.y;j++){
			ans.s[i][j]=0;
			for(int k=1;k<=mtx1.y;k++)
				ans.s[i][j]=(ans.s[i][j]+mtx1.s[i][k]*mtx2.s[k][j])%mod;
		}
	return ans;
}

Operator定義運算

可以定義運算符,讓程序比較簡潔。
示例:重載 + 為高精度加法:
operator+(a,b:sz)c:sz;
vari,ni:longint;
begin
fillchar(c,sizeof(c),0);
ni:=a[0];
ifni<b[0]thenni:=b[0];
fori:=1tonido
begin
c[i]:=c[i]+b[i]+a[i];
ifc[i]>9then
begin
inc(c[i+1],c[i]div10);
c[i]:=c[i]mod10;
end;
end;
ifc[ni+1]>0theninc(ni);
c[0]:=ni;
end.