C++ 关键字 explicit

来源:互联网 发布:所有教材答案软件 编辑:程序博客网 时间:2024/05/27 10:44

C++用 explicit 关键字来修饰类的构造函数,表明函数是显式的,在介绍显式构造函数之前,我们先来看一下隐式构造函数:

#include <iostream>using namespace std;class MyString{public:MyString(int n){ cout<<"constructor from int"<<endl; }MyString(char* p){ cout<<"constructor from char*"<<endl; }};int main(){MyString str = 10;MyString str1 = "hello";return 0;}

WindowXP+VS2008下 运行结果输出:

constructor from int
constructor from char*


在上面的代码中编译器自动将整型转换为MyString类对象,实际上等同于下面的操作:

MyString temp(10);MyString str = temp;
MyString temp("hello");MyString str1 = temp;
在C++中如果类的构造函数只有一个参数,那么编译的时候就会有个缺省的操作:将该构造函数对应数据类型的数据转换为该类对象,这就是隐式构造函数。看上去很方便,但如果你并不希望如此通过转换生成一个新对象的话, 麻烦也随之而来,为避免构造函数被调用造成隐式转换, 可以将其声明为 explicit,也就是显示构造函数

#include <iostream>using namespace std;class MyString{public:explicit MyString(int n){ cout<<"constructor from int"<<endl; }explicit MyString(char* p){ cout<<"constructor from char*"<<endl; }};int main(){MyString str = 10;MyString str1 = "hello";return 0;}

此时编译就会出现错误:

error C2440: 'initializing' : cannot convert from 'int' to 'MyString' explicit.cpp 14
error C2440: 'initializing' : cannot convert from 'const char [6]' to 'MyString' explicit.cpp 15


在 Google C++编码规范中,对单个参数的构造函数规定要求必须使用 C++ 关键字 explicit,除了在一些极少数情况下








2 0
原创粉丝点击