隱式類型轉換
#include <iostream>
using namespace std;class Point {
public:int x, y;Point(int x = 0, int y = 0): x(x), y(y) {}
};void displayPoint(const Point& p)
{cout << "(" << p.x << "," << p.y << ")" << endl;
}int main()
{displayPoint(1);Point p = 1;
}
它的構造函數使用了默認參數. 這時主函數里的兩句話都會觸發該構造函數的隱式調用. (如果構造函數不使用默認參數, 會在編譯時報錯)
函數displayPoint需要的是Point類型的參數, 而我們傳入的是一個int, 這個程序卻能成功運行, 就是因為這隱式調用.
程序的輸出結果為(1,0)
此外,在對象剛剛定義時, 即使你使用的是賦值操作符=, 也是會調用構造函數, 而不是重載的operator=運算符.
explicit關鍵字
上述發生的事情,有時可以帶來好處,但有時也會帶來意想不到的后果;explicit是防止類構造函數的隱式自動轉換。
#include <iostream>
using namespace std;class Point {
public:int x, y;explicit Point(int x = 0, int y = 0): x(x), y(y) {}
};void displayPoint(const Point& p)
{cout << "(" << p.x << "," << p.y << ")" << endl;
}int main()
{displayPoint(Point(1));Point p(1);
}