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

    explicit是c++中不太常用的一个关键字,其作用是用于修饰构造函数,告诉编译器定义对象时不做隐式转换。

    举例说明:

    include <iostream>
    include <string>
    using namespace std;
    class person
    {
    public:
        person(int age);
        person(int age,string name);
    private:
        int age;
        string name;
    };
    
    int main(int argc,char* argv)
    {
        person p = 23;//此处语法没问题,=>person p = person(23);
        return 0;
    }
    
    person::person(int age)
    {
        this->age = age;
    }
    person::person(int age,string name)
    {
        this->age = age;
        this->name = name;
    }

    person p =23;这行代码没任何问题,因为person类中有一个person(int age)构造函数,gcc、cl等编译器会隐式调用此构造函数创建对象。
    如果在person(int age)构造函数前加explicit关键字则编译无法通过。

    include <iostream>
    include <string>
    using namespace std;
    class person
    {
    public:
        explicit person(int age);//此处增加explicit关键字
        person(int age,string name);
    private:
        int age;
        string name;
    };
    
    int main(int argc,char* argv)
    {
        person p = 23;
        return 0;
    }
    
    person::person(int age)
    {
        this->age = age;
    }
    person::person(int age,string name)
    {
        this->age = age;
        this->name = name;
    }

    编译时g++编译器报:
    error: conversion from int' to non-scalar typeperson’ requested

  • 相关阅读:
    linux 和unix 的区别
    Ubuntu 12.04下安装ibus中文输入法
    安装vmware tools失败解决方法
    snort简介以及在Ubuntu下的安装
    ubuntu下tcpdump使用
    securecrt在linux与windows之间传输文件(转)
    大数据处理时用到maven的repository
    Spark之命令
    Spark之集群搭建
    Spark之scala
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6469031.html
Copyright © 2011-2022 走看看