一、提要
面向对象规则中,在对象生成的时候,存在隐式和显式两个方式。隐式调用构造函数,使得调用很灵活。但是,有些情况必须显式,此时可以选择“必须显式”的模式。explicit就是限定构造函数,使其只能显式调用,不能隐式转换的关键词。
二、隐式转换是什么?
看一下这种隐式类型转换是怎么发生的吧.
#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)
{
std::cout << "(" << p.x << "," << p.y << ")" << std::endl;
}
int main()
{
displayPoint(1);
Point p=30 ;
displayPoint(p );
}
以上的隐式转化有两个:
1) displayPoint(1); 此处的“1”是这样得到的:<