您的位置:首页 > 编程语言 > C语言/C++

C++中explicit关键字作用

2015-04-08 13:29 459 查看

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 type
person’ requested
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: