国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(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)鍵字的評論 (共 條)

分享到微博請遵守國家法律
泽普县| 五寨县| 蒙山县| 中江县| 苍山县| 宁强县| 卓资县| 汕头市| 澄江县| 涡阳县| 富蕴县| 无锡市| 荆州市| 扬中市| 台安县| 东乌珠穆沁旗| 石棉县| 神池县| 兴安盟| 漠河县| 当涂县| 长丰县| 天台县| 安达市| 东宁县| 马边| 金昌市| 泽库县| 天全县| 墨竹工卡县| 东乌| 庆城县| 灌阳县| 杭锦旗| 崇礼县| 金川县| 若羌县| 清丰县| 堆龙德庆县| 三门峡市| 广平县|