c++運算子多載基礎知識詳解_C 語言

來源:互聯網
上載者:User

實際上,很多C++運算子已經被重載。eg:將*運算子用於地址,將得到儲存在這個地址中的值,將他用於2個數字時,得到的將是他們的乘積。C++根據運算元的數目和類型來決定採用哪種操作。

C++允許將運算子多載擴充到使用者定義的類型。例如,允許使用+將兩個對象相加。編譯器將根據運算元的數目和類型決定使用加法定義。運算子多載可以使代碼看起來更自然。例如,將2個數組相加是一種常見的運算。通常,需要使用下面這樣的for迴圈來實現:

複製代碼 代碼如下:

for (int i = 0; i < 20; i++)
evening[i] = sam[i] + janet[i]; // add element by element

但在C++中,可以定義一個表示數組的類,並重載+運算子,於是便有這樣的語句:

total = arr1+arr2;
一個計算時間的例子
mytime.h

複製代碼 代碼如下:

#include"stdafx.h"
#include"MyTime.h"
#include<iostream>

int_tmain(intargc,_TCHAR*argv[])
{
//比匯入整個名稱空間更經濟
usingstd::cout;
usingstd::endl;

Timeplanning;
Timecoding(2,50);
Timefixing(5,55);
Timetotal;
cout<<"planningtime=";
planning.Show();
cout<<endl;
cout<<"codingtime=";
coding.Show();
cout<<endl;
cout<<"fixingtime=";
fixing.Show();
cout<<endl;
total=coding.Sum(fixing);
cout<<"coding.Sum(fixing)=";
total.Show();
cout<<endl;
total=coding+fixing;
cout<<"coding+fixing=";
total.Show();
cout<<endl;
getchar();
return0;
}

調用

複製代碼 代碼如下:

#include"stdafx.h"
#include"MyTime.h"
#include<iostream>

int_tmain(intargc,_TCHAR*argv[])
{
//比匯入整個名稱空間更經濟
usingstd::cout;
usingstd::endl;

Timeplanning;
Timecoding(2,50);
Timefixing(5,55);
Timetotal;
cout<<"planningtime=";
planning.Show();
cout<<endl;
cout<<"codingtime=";
coding.Show();
cout<<endl;
cout<<"fixingtime=";
fixing.Show();
cout<<endl;
total=coding.Sum(fixing);
cout<<"coding.Sum(fixing)=";
total.Show();
cout<<endl;
total=coding+fixing;
cout<<"coding+fixing=";
total.Show();
cout<<endl;
getchar();
return0;
}

執行結果

重點講解
1.sum函數中將參數聲明為引用,可以提高運行效率,節省記憶體

2.sum函數中,傳回值不能是引用。因為sum對象是局部變數,在函數結束時將被刪除,因此引用將指向一個不存在的對象。使用傳回型別Time意味著在刪除sum之前構造他的拷貝,調用函數將得到他的拷貝。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.