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

  • 相关阅读:
    计算几何
    HDU 4267
    HDU 4277
    NYOJ 123(插线问点)
    Set
    HDU 1792
    从文本文件读取数据到用vector实现的二维数组中
    为什么计算机采用二进制而不是八进制或者十六进制
    Google C++编程风格指南1
    编程中的命名设计
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6469031.html
Copyright © 2011-2022 走看看