c/c++整理--c++面向对象(5)
生活随笔
收集整理的這篇文章主要介紹了
c/c++整理--c++面向对象(5)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
構(gòu)造函數(shù)的使用
以下代碼中的輸出語句為0嗎?為什么?
#include <iostream> using namespace std; struct CLS { int m_i; CLS(int i):m_i(i){ } CLS() { CLS(0); } }; int main() { CLS obj; cout<<obj.m_i<<endl; return 0; }在代碼第11行,不帶參數(shù)的構(gòu)造函數(shù)調(diào)用了帶參數(shù)的構(gòu)造函數(shù)。這種調(diào)用往往被很多人誤解,其實是不行的,而且往往會有副作用。可以加幾條打印語句測試一下:
#include <iostream> using namespace std; struct CLS { int m_i; CLS(int i):m_i(i) { cout<<"CLS():this= "<<this<<endl; } CLS() { CLS(0); cout<<"CLS():this= "<<this<<endl; } }; int main() { CLS obj; cout<<"&obj= "<<&obj<<endl; cout<<obj.m_i<<endl; return 0; } 程序執(zhí)行結(jié)果: CLS():this= 0xbffa176c CLS():this= 0xbffa179c &obj= 0xbfe7391c 7823348可以看到,在帶參數(shù)的構(gòu)造函數(shù)里打印出來的對象地址和對象obj的地址不一致。實際上,代碼14行的調(diào)用只是在棧上生成了一個臨時對象,對于自己本身毫無影響。還可以發(fā)現(xiàn),構(gòu)造函數(shù)的相互調(diào)用引起的后果不是死循環(huán),而是棧溢出。
構(gòu)造函數(shù)explicit與普通構(gòu)造函數(shù)的區(qū)別
explicit構(gòu)造函數(shù)是用來防止隱式轉(zhuǎn)換的。
#include <iostream> using namespace std; class Test1 { public: Test1(int n) { num = n; } //普通構(gòu)造函數(shù) private: int num; }; class Test2 { public: explicit Test2(int n) { num = n; } //explicit(顯示)構(gòu)造函數(shù) private: int num; }; int main() { Test1 t1 = 12; //隱式調(diào)用其構(gòu)造函數(shù),成功 Test2 t2 = 12; //編譯錯誤,不能隱式調(diào)用其構(gòu)造函數(shù) Test2 t3(12); //顯示調(diào)用成功 return 0; }Test1的構(gòu)造函數(shù)帶一個int型參數(shù),代碼第21行會隱式轉(zhuǎn)換成調(diào)用Test1的構(gòu)造函數(shù)。而Test2的構(gòu)造函數(shù)被聲明為explicit(顯示),這表示不能通過隱式轉(zhuǎn)換來調(diào)用這個構(gòu)造函數(shù),因此22行編譯錯誤。
explicit構(gòu)造函數(shù)的作用
#include <iostream> using namespace std; class Number { public: string type; Number():type("void"){} explicit Number(short):type("short") {} Number(int):type("int"){ } }; void show(const Number& n) { cout<<n.type<<endl; } int main() { short s=42; show(s); return 0; }show()函數(shù)的參數(shù)類型是Number類對象的引用,18行調(diào)用show(s)時采取了以下所示的步驟:
(1)show(s)中的s為short類型,其值為42,因此首先檢查參數(shù)為short的構(gòu)造函數(shù)能否被隱式轉(zhuǎn)換。由于第9行的構(gòu)造函數(shù)被聲明為explicit(顯示調(diào)用),因此不能隱式轉(zhuǎn)換。于是進行下一步。
(2)42自動轉(zhuǎn)換為int型。
(3)檢查參數(shù)為int的構(gòu)造函數(shù)能否被隱式轉(zhuǎn)換。由于第10行參數(shù)為int的構(gòu)造函數(shù)嗎,沒有被聲明為顯示調(diào)用,因此此構(gòu)造函數(shù)臨時構(gòu)造出一個臨時對象。
(4)打印上一步臨時對象type的成員,即“int”
總結(jié)
以上是生活随笔為你收集整理的c/c++整理--c++面向对象(5)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GJB 软件质量保证报告(模板)
- 下一篇: notify_one() 或 notif