C++運算子多載(5) 重載== explicit避免隱式轉換__C++

來源:互聯網
上載者:User

有的時候程式中存在隱藏式轉換

比如下面這個例子

#include<iostream>using namespace std;class myComplex {private:int real;   //複數的實部int image;  //複數的虛部public:myComplex(int real = 0, int image = 0) {this->real = real;this->image = image;}friend bool operator == (const myComplex &obj1, const myComplex &obj2);};bool operator == (const myComplex &obj1, const myComplex &obj2) {if (obj1.real == obj2.real && obj1.image == obj2.image)return true;return false;}int main() {myComplex TestA(3,0);myComplex TestB(10,0);if (TestA == 3) {cout << "SAME" << endl;}else {cout << "NOT SAME" << endl;}system("PAUSE");return 0;

我們通過重載操作符 == 來判斷兩個自訂的類:複數是否相等

myComplex(int real = 0, int image = 0)
在建構函式中,我們給形參定義了預設值 所以在產生對象時 如果不指定形參 便會使用預設值

C++中,如果建構函式可以只傳入一個參數來調用,則會發生隱式轉換

if (TestA == 3)
在上面行代碼中 將3傳入重載操作符函數 建構函式便會構造一個3,0的myComplex對象, 這便發生了隱式轉換(將int型轉為myComplex型)

我們可以通過使用explicit來避免隱式轉換

explicit myComplex(int real = 0, int image = 0) {this->real = real;this->image = image;}

這時必須指明類型

myComplex TestA(3,0);myComplex TestB(10,0);if (TestA == (myComplex)3) {    //必須指明類型cout << "SAME" << endl;}else {cout << "NOT SAME" << endl;}






聯繫我們

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