標籤:amp exp logs ace names 編譯 輸出 void xpl
一、重載運算子法
#include <stdio.h>#include <iostream>class Three{ int i;public: Three(int ii = 0, int = 0) : i(ii) { std::cout << "you call Three()" << std::endl; }};class Four{ int x;public: Four(int xx) : x(xx) {} operator Three() const { return Three(x);}};void g(Three) {}int main(){ Four four(1); g(four); g(1);//calls Three(1,0) int n; std::cin >> n;}
//輸出兩次:
you call Three()
2.建構函式轉換
//這個建構函式能夠把另一類型的對象(引用)作為它的單個參數,那麼建構函式允許編譯器執行自動類型轉換;
#include <stdio.h>#include <iostream>class One{public: One() {} };class Two{public: Two(const One&) { std::cout << "you call Two()" << std::endl; }};void f(Two) {}int main(){ One one; f(one);//wants a Two ,has a one
//輸出:"you call Two()”
int i; std::cin >> i;}
注意:以上方法調用了Two的隱藏的建構函式,如果關心調用效率的話不要這樣使用!
3.阻止建構函式被隱式調用,要求必須顯示調用:
//使用關鍵詞explicit時,必須顯示調用,完成類型轉換
#include <stdio.h>#include <iostream>using namespace std;class One{public: One() { }};class Two{public: explicit Two(const One&) {}};void f(Two) {}int main(){ One one; //!f(one);//NO auto conversion allowed f(Two(one)); //int i; //cin >> i;}
C++自動類型轉化--特殊建構函式方法和重載的運算子方法