C++ 中顯式關鍵字的使用\n
接下來,我們來看看關鍵字顯式在 C++ 中的作用。在討論之前,讓我們看一個示例程式碼,並嘗試找出其輸出。
示例
#include <iostream> using namespace std; class Point { private: double x, y; public: Point(double a = 0.0, double b = 0.0) : x(a), y(b) { //constructor } bool operator==(Point p2) { if(p2.x == this->x && p2.y == this->y) return true; return false; } }; int main() { Point p(5, 0); if(p == 5) cout << "They are same"; else cout << "They are not same"; }
輸出
They are same
此程式碼工作正常,這是因為我們知道,如果僅可以使用一個引數呼叫一個建構函式,則它將轉換到轉換建構函式。但是,我們可以避免此類轉換,因為這可能會產生一些不可靠的結果。
為了限制此轉換,我們可以在建構函式中使用顯式修飾符。在這種情況下,該建構函式不會被轉換。如果使用顯式關鍵字使用上述程式,則它將產生編譯錯誤。
示例
#include <iostream> using namespace std; class Point { private: double x, y; public: explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) { //constructor } bool operator==(Point p2) { if(p2.x == this->x && p2.y == this->y) return true; return false; } }; int main() { Point p(5, 0); if(p == 5) cout << "They are same"; else cout << "They are not same"; }
輸出
[Error] no match for 'operator==' (operand types are 'Point' and 'int') [Note] candidates are: [Note] bool Point::operator==(Point)
我們仍然可以透過使用顯式強制轉換將值強制轉換為 Point 型別。
示例
#include <iostream> using namespace std; class Point { private: double x, y; public: explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) { //constructor } bool operator==(Point p2) { if(p2.x == this->x && p2.y == this->y) return true; return false; } }; int main() { Point p(5, 0); if(p == (Point)5) cout << "They are same"; else cout << "They are not same"; }
輸出
They are same
廣告