c++基础 explicit

时间:2022-04-25
本文章向大家介绍c++基础 explicit,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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");