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

 

 

posted @ 2014-04-04 15:22  li-peng  阅读(382)  评论(0编辑  收藏  举报