C++ explicit关键字的作用

explicit关键字只针带一个参数的构造函数有效

cpp 复制代码
#include <iostream>
using namespace std;

class A
{
public:
  A(int temp) //普通构造函数
  {
    a = temp;
    cout << "普通构造函数: a= " << a << endl;
  }
  
  A(const A &temp) //拷贝构造函数
  {
    a = temp.a;
    cout << "拷贝构造函数: a = " << a << endl;
  }
  
private:
  int a;
};

int main()
{
  cout << "显示调用:" << endl;
  A a(250); //显式调用调用普通构造函数,ok
  A b(a);   //显式调用调用拷贝构造函数,ok
  
  cout << "\n隐式转换:" << endl;
  A c=222; //隐式转换成调用普通构造函数,ok
  A d=c;   //隐式转换成调用拷贝构造函数,ok

  return 0;  
}

使用explicit关键字后

cpp 复制代码
#include <iostream>
using namespace std;

class A
{
public:
  explicit A(int temp) //普通构造函数,被声明为explicit(显式)
  {
    a = temp;
    cout << "普通构造函数: a= " << a << endl;
  }
  
  A(const A &temp) //拷贝构造函数,被声明为explicit(显式)
  {
    a = temp.a;
    cout << "拷贝构造函数: a = " << a << endl;
  }
  
private:
  int a;
};

int main()
{
  cout << "显示调用:" << endl;
  A a(250); //显式调用调用普通构造函数,ok
  A b(a);   //显式调用调用拷贝构造函数,ok
  
  //explicit构造函数只能被显式调用
  A c=222; //不能通过隐式转换,error
  A d=c;   //不能通过隐式转换,error

  return 0;  
}
相关推荐
沐知全栈开发8 小时前
HTML5 浏览器支持
开发语言
wasp5208 小时前
AgentScope Java 核心架构深度解析
java·开发语言·人工智能·架构·agentscope
WHOVENLY8 小时前
【javaScript】- 笔试题合集(长期更新,建议收藏,目前已更新至31题)
开发语言·前端·javascript
慌糖8 小时前
流-为序列化解释
开发语言
LXS_3579 小时前
Day 18 C++提高 之 STL常用容器(string、vector、deque)
开发语言·c++·笔记·学习方法·改行学it
王琦03189 小时前
Python 函数详解
开发语言·python
胡伯来了9 小时前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…9 小时前
Python 中的多层继承
开发语言·python
deng-c-f10 小时前
Linux C/C++ 学习日记(53):原子操作(二):实现shared_ptr
开发语言·c++·学习
wanghowie10 小时前
01.07 Java基础篇|函数式编程与语言新特性总览
java·开发语言·面试