C++ explicit

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

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

// spec1_explicit.cpp
// compile with: /EHsc
#include <stdio.h>

class C 
{
public:
    int i;
    explicit C(const C&)   // an explicit copy constructor
    {
        printf_s("\nin the copy constructor");
    }
    explicit C(int i )   // an explicit constructor
    {
        printf_s("\nin the constructor");
    }

    C()
    {
        i = 0;
    }
};

class C2
{
public:
    int i;
    explicit C2(int i )   // an explicit constructor
    {
    } 
};

C f(C c)
{   // C2558
    c.i = 2;
    return c;   // first call to copy constructor
}

void f2(C2)
{
}

void g(int i)
{
    f2(i);   // C2558
    
// try the following line instead
    
// f2(C2(i));
}

int main()
{
    C c, d;
    const C &cc= c;
    const C &ccc= c;
    ccc.C::C(cc);
    d = f(c);   // c is copied
}

 

原文链接: https://www.cnblogs.com/whyandinside/archive/2012/05/12/2497398.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ explicit

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/50046

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午1:40
下一篇 2023年2月9日 上午1:41

相关推荐