您好,登錄后才能下訂單哦!
這篇文章主要介紹C++中隱式類型轉(zhuǎn)換的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
1 operator隱式類型轉(zhuǎn)換
1.1 std::ref源碼中reference_wrapper隱式類型轉(zhuǎn)換
在std::ref的實現(xiàn)中有如下一段代碼:
template<typename _Tp> class reference_wrapper : public _Reference_wrapper_base<typename remove_cv<_Tp>::type> { _Tp* _M_data; public: typedef _Tp type; reference_wrapper(_Tp& __indata) noexcept : _M_data(std::__addressof(__indata)) { } reference_wrapper(_Tp&&) = delete; reference_wrapper(const reference_wrapper&) = default; reference_wrapper& operator=(const reference_wrapper&) = default; //operator的隱式類型轉(zhuǎn)換 operator _Tp&() const noexcept { return this->get(); } _Tp& get() const noexcept { return *_M_data; } template<typename... _Args> typename result_of<_Tp&(_Args&&...)>::type operator()(_Args&&... __args) const { return __invoke(get(), std::forward<_Args>(__args)...); } };
注意看operator操作符重載:
operator _Tp&() const noexcept { return this->get(); }
就是用于類型轉(zhuǎn)換。
1.2 簡單的例子-實現(xiàn)一個class轉(zhuǎn)為int的示例
#include <iostream> /* * * c++ operator的隱式類型轉(zhuǎn)換 * 參見std::ref的實現(xiàn) */ void f(int a) { std::cout << "a = " << a << std::endl; } class A{ public: A(int a):num(a){} ~A() {} operator int() { return num; } int num; }; int main() { A a(1); std::cout << a + 1 << std::endl; f(a); return 0; }
當然除了通過operator實現(xiàn)隱式類型轉(zhuǎn)換,c++中還可以通過構(gòu)造函數(shù)實現(xiàn)。
2 構(gòu)造函數(shù)實現(xiàn)隱式類型轉(zhuǎn)換
在c++ primer一書中提到
可以用單個實參來調(diào)用的構(gòu)造函數(shù)定義了從形參類型到該類類型的一個轉(zhuǎn)換
看如下示例:
#include <iostream> /* * * c++ 構(gòu)造的隱式類型轉(zhuǎn)換 * 參見std::ref的實現(xiàn) */ class B{ public: B(int a):num(a){} ~B() {} int num; }; class A{ public: A(int a):num(a){} A(B b):num(b.num){} ~A() {} int fun(A a) { std::cout << num + a.num << std::endl; } int num; }; int main() { B b(1); A a(2); //通過構(gòu)造函數(shù)實現(xiàn)了隱式類型轉(zhuǎn)換 a.fun(b); //輸出結(jié)果為3 return 0; }
特別需要注意的是單個實參,構(gòu)造函數(shù)才會有隱式轉(zhuǎn)換,一個條件不滿足都是不行。
3 使用explicit關(guān)鍵字避免構(gòu)造函數(shù)隱式轉(zhuǎn)換
有些時候我們并不希望發(fā)生隱式轉(zhuǎn)換,不期望的隱式轉(zhuǎn)換可能出現(xiàn)意外的結(jié)果,explicit關(guān)鍵詞可以禁止之類隱式轉(zhuǎn)換,將上述class A的構(gòu)造函數(shù)改為如下
class A{ public: A(int a):num(a){} explicit A(B b):num(b.num){} ~A() {} int fun(A a) { std::cout << num + a.num << std::endl; } int num; };
再次運行程序出現(xiàn)提示:
op2.cpp: In function ‘int main()':
op2.cpp:29:12: error: no matching function for call to ‘A::fun(B&)'
a.fun(b);
^
op2.cpp:16:9: note: candidate: int A::fun(A)
int fun(A a)
^~~
op2.cpp:16:9: note: no known conversion for argument 1 from ‘B' to ‘A'
這個時候調(diào)用方式修改更改為:
int main() { B b(1); A a(2); a.fun(A(b)); return 0; }
以上是“C++中隱式類型轉(zhuǎn)換的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。