五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

C/C++編程筆記:在C++中使用顯式關(guān)鍵字

2021-04-27 20:13 作者:C語言編程__Plus  | 我要投稿



首先,我們看一看下面這個C ++程序的輸出。

#include <iostream>

using namespace std;

class Complex

{

private:

double real;

double imag;

public:

// Default constructor

Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

// A method to compare two Complex numbers

bool operator == (Complex rhs) {

return (real == rhs.real && imag == rhs.imag)? true : false;

}

};

int main()

{

// a Complex object

Complex com1(3.0, 0.0);

if (com1 == 3.0)

cout << "Same";

else

cout << "Not Same";

return 0;

}

輸出:程序編譯正常,并產(chǎn)生以下輸出。

Same

在C ++中,如果類具有可以用單個參數(shù)調(diào)用的構(gòu)造函數(shù),則該構(gòu)造函數(shù)將成為轉(zhuǎn)換構(gòu)造函數(shù),因為這樣的構(gòu)造函數(shù)允許將單個參數(shù)轉(zhuǎn)換為正在構(gòu)造的類。

我們可以避免這種隱式轉(zhuǎn)換,因為它們可能導(dǎo)致意外的結(jié)果。例如,如果嘗試下面的程序,該程序使用帶有構(gòu)造函數(shù)的顯式關(guān)鍵字,則會出現(xiàn)編譯錯誤。

#include <iostream>

using namespace std;

class Complex

{

private:

double real;

double imag;

public:

// Default constructor

explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

// A method to compare two Complex numbers

bool operator== (Complex rhs) {

return (real == rhs.real && imag == rhs.imag)? true : false;

}

};

int main()

{

// a Complex object

Complex com1(3.0, 0.0);

if (com1 == 3.0)

cout << "Same";

else

cout << "Not Same";

return 0;

}

輸出:編譯器錯誤

在'com1 == 3.0e + 0'中找不到'operator =='的匹配項

我們?nèi)匀豢梢詫ouble值類型轉(zhuǎn)換為Complex,但是現(xiàn)在我們必須顯式類型轉(zhuǎn)換。例如,以下程序可以正常運行。

#include <iostream>

using namespace std;

class Complex

{

private:

double real;

double imag;

public:

// Default constructor

explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

// A method to compare two Complex numbers

bool operator== (Complex rhs) {

return (real == rhs.real && imag == rhs.imag)? true : false;

}

};

int main()

{

// a Complex object

Complex com1(3.0, 0.0);

if (com1 == (Complex)3.0)

cout << "Same";

else

cout << "Not Same";

return 0;

}

輸出:程序編譯正常,并產(chǎn)生以下輸出。

Same

以上就是今天的全部內(nèi)容了。每日分享小知識,希望對你有幫助~

另外如果你想更好的提升你的編程能力,學(xué)好C語言C++編程!彎道超車,快人一步!筆者這里或許可以幫到你~

微信公眾號:C語言編程學(xué)習(xí)基地

分享(源碼、項目實戰(zhàn)視頻、項目筆記,基礎(chǔ)入門教程)

歡迎轉(zhuǎn)行和學(xué)習(xí)編程的伙伴,利用更多的資料學(xué)習(xí)成長比自己琢磨更快哦!


C/C++編程筆記:在C++中使用顯式關(guān)鍵字的評論 (共 條)

分享到微博請遵守國家法律
林口县| 霍邱县| 明光市| 灯塔市| 新民市| 渭南市| 靖西县| 湖州市| 平定县| 封丘县| 丹棱县| 开远市| 板桥市| 伊金霍洛旗| 甘洛县| 凤阳县| 湖州市| 大余县| 博湖县| 尚志市| 江津市| 屏东市| 阜南县| 邵武市| 澄城县| 苏尼特右旗| 交城县| 德安县| 湖南省| 独山县| 彭阳县| 白山市| 绍兴县| 山阴县| 始兴县| 宁化县| 新余市| 保靖县| 离岛区| 泰兴市| 双江|