ที่นี่เราจะมาดูกันว่าอะไรคือผลกระทบของคำหลักที่ชัดเจนใน 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
วิธีนี้ใช้ได้ผลดีเพราะเรารู้ว่าหากสามารถเรียกคอนสตรัคเตอร์หนึ่งตัวโดยใช้อาร์กิวเมนต์เดียวเท่านั้น คอนสตรัคเตอร์ก็จะถูกแปลงเป็นคอนสตรัคเตอร์ แต่เราสามารถหลีกเลี่ยง Conversion ประเภทนี้ได้ เนื่องจากอาจทำให้ได้ผลลัพธ์ที่ไม่น่าเชื่อถือ
เพื่อจำกัดการแปลงนี้ เราสามารถใช้ตัวแก้ไขที่ชัดเจนกับตัวสร้าง ในกรณีนี้จะไม่ถูกแปลง หากใช้โปรแกรมด้านบนโดยใช้คีย์เวิร์ดที่ชัดเจน จะทำให้เกิดข้อผิดพลาดในการรวบรวม
ตัวอย่าง
#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