可以用单个形参来调用的构造函数定义了从形参类型到该类类型的一个隐式转换。
```c++
class A {
public:
explicit A(int a) {
printf("%d\n", a);
}
~A() {}
};
int main() {
double d = 4.5;
A b(d); // 显式调用,可编译
A a = d; // 隐式调用,不可编译
return 0;
}
```
## 构造函数禁用隐式调用构造
当自定义类存在一个构造函数使用指针作为参数时,需要使用 `explicit` 关键字修饰构造函数,否则可能会存在隐式构造函数调用,将数值 0 转换成该类。
```c++
class Student {
public:
Student() : _data(NULL) {}
explicit Student(const int* data) : _data(data) {}
~Student() {}
bool operator ==(const Student& rhs) const {
if (!this->_data || !rhs._data) {
return false;
}
return *this->_data == *rhs._data;
}
bool operator !=(const Student& rhs) const {
return !(*this == rhs);
}
private:
const int* _data;
};
int main () {
int c = 19;
Student p_c(&c);
if (p_c != 0) { // 如果构造函数没有 explicit 修饰,这里编译器将无法检查
printf("yes!\n");
}
return 0;
}
```
- 目录
- 基础知识
- 1、变量和基础类型
- 1.1、内置类型
- 1.2、变量
- 1.3、复合类型
- 1.4、类型修饰符
- 1.5、类型处理
- 1.6、自定义结构
- 1.7、数组
- 2、表达式和语句
- 2.1、运算符
- 2.2、语句
- 3、函数
- 1、语法相关
- 2、资源管理
- 3、面向对象
- 4、模板与泛型编程
- Problem01:判断类中是否包含函数
- Problem02:解析函数的参数类型
- 5、系统库
- Problem01:多线程维护最大值
- Problem02:介绍一下strcpy、strncpy、memcpy、memmove
- Problem03:介绍一下网络编程
- Problem04:select、poll、epoll的区别
- 未整理
- Problem11:实现在main函数前、后执行的函数
- Problem12:可变参函数的实现
- Problem13:全局变量初始化顺序问题
- Problem14:介绍一下隐式转换
- Problem07:实现一个不能被拷贝的类
- Problem08:实现一个只能通过动态、静态分配的类
- 开源项目
- redis
- 第一部分 数据结构与对象
- redis 底层数据结构
- redis 对象
- taskflow
- 数据结构
- Executor
