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

posted on 2015-04-08 13:29  岚之山  阅读(156)  评论(0编辑  收藏  举报

导航