zoukankan      html  css  js  c++  java
  • C++关键字explicit

         explicit的中文解译是:详尽的;清楚的;明确的。那么explicit在C++中是什么意思呢?

    Explicit(显示的)

    (1)explicit可以禁止“单参数构造函数”被用于自动类型转换,有效的防止了构造函数的隐式转换带来的错误。

    (2)explicit只对构造函数起作用,用来抑制隐式转换。

    (3)所有的单参数的构造函数都必须是explicit的,以避免后台的类型转换。

    用实例说明上面两点:

    #include <iostream>
    using namespace std;

    class People
    {
    public:
    People(int age){}
    People(string name){this->name=name;}
    int age;
    string name;
    };

    int main()
    {
    People people1(25);
    People people2=25;

    return 0;
    }

    上面的People people2=25编译竟然能够通过,将25赋给人,有点说不过去。为了避免这种情况发生就需要在构造函数上加关键字explicit了,程序如下:

    #include <iostream>
    using namespace std;

    class People
    {
    public:
    explicit People(int age){}
    People(string name){this->name=name;}
    int age;
    string name;
    };

    int main()
    {
    People people1(25);
    //People people2=25; //error C2440: 'initializing' : cannot convert from 'const int' to 'class People'

    return 0;
    }

    加上关键字explicit后,People people2=25就编译通不过了。

  • 相关阅读:
    设计模式-适配器模式
    设计模式-模板方法模式
    设计模式-策略模式
    spring-消息
    spring-集成redis
    spring-mvc高级技术
    spring-AOP
    restful规范
    十一,装饰器详解
    十,函数对象,嵌套,名称空间与作用域,闭包函数
  • 原文地址:https://www.cnblogs.com/danshui/p/2313631.html
Copyright © 2011-2022 走看看