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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP