explicit

来源:互联网 发布:淘宝店团队管理要点 编辑:程序博客网 时间:2024/04/28 07:58

c++的构造函数也定义了一个隐式转换

explicit只对构造函数起作用,用来抑制隐式转换

看一个小例子

新建一个头文件

#ifndef CMYSTRING_H#define CMYSTRING_H#include<string>#include<iostream>using namespace std;class CMyString{public:CMyString(const char * str);void SetString(string str);};#endif // CMYSTRING_H
#include "CMyString.h"CMyString::CMyString(const char * str){    std::cout<<str;}void CMyString::SetString(string str){    std::cout<<str;}

在调用 的时候

可以直接这么调用构造函数

CMyString my1="ab";

加上explicit

#ifndef CMYSTRING_H#define CMYSTRING_H#include<string>#include<iostream>using namespace std;class CMyString{public:explicit CMyString(const char * str);void SetString(string str);};#endif // CMYSTRING_H

之后再和上面一样调用就不会通过了

只能是

CMyString my1("ab");


0 0
原创粉丝点击