C++ explicit

好久没写博客了,这些天看effective C++积攒下不少疑问,今天就看到个。
关于explicit的,本身没什么特殊含义,用来声明构造函数不能发生隐式类型转换的,查资料又对构造函数有些理解,故此记录下~

C++中, 一个参数的构造函数, 承担了两个角色。 1 是个构造器 2 是个默认且隐含的类型转换操作符。

例如下面例子中C的构造函数C(int i)就是,既可以用来作为构造器,又可以实现隐式转换C c=2;但是有时这并不是我们想要的,就可以将这个构造函数声明为explicit,以避免将构造函数作为隐式类型转换符来使用。Copy constructor也是同样的,如果Copy constructor被声明为explicit,则这个类对象不能用于传参和函数返回值。但是仍然可以直接调用。。

#include <iostream>
#include <string>

class mystring {
public:
    explicit mystring(const char* p);
    explicit mystring(int n);
};

mystring::mystring( const char* p )
{
    std::cout << p << std::endl;
}

mystring::mystring( int n )
{
    std::cout << n << std::endl;
}

int main(int argc, char *argv[], char *env[])
{
    const char *c = "Hello World!!!";
    int i = 4;

    mystring mystr1 = mystring(c);//ok
    mystring mystr2 = mystring(i);//ok

    // 构造函数加上关键字explicit,下面两句编译都过不去
    // 因为此时这种隐式转换不允许
    // 所以为了避免二意义性,单参数的构造函数建议要加上explicit
    mystring mystr3 = c;    // error,不允许隐式的转换
    mystring mystr4 = i;    // error,不允许隐式的转换

    return 0;
}

posted on 2015-06-18 23:12  泉山绿树  阅读(26)  评论(0)    收藏  举报

导航