显式(C++)

自动具有一个参数执行隐式类型转换的 C++ 构造函数。 例如,因此,如果您通过 int ,则构造函数需要字符串指针参数,则必须将 int 转换为字符串指针的编译器将添加代码。 但是,您可能不会始终需要此自动行为。

可以添加 explicit 到构造函数声明防止隐式转换。 这可以强制代码以使用正确类型的参数或者将该参数设置为正确的类型。 也就是说,如果转换使用代码不明显表示,就会发生错误。

explicit 关键字只能应用于类构造函数声明显式构造对象。

示例

编译下面的过程将导致错误。 代码尝试执行隐式转换,但是,对 explicit关键字的用法阻止它。 解决错误,移除 explicit 关键字和调整。 g的代码。

// 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;
    d = f(c);   // c is copied
}

声明有多个参数的 explicit 的构造函数不起作用,因为这样,构造函数不能在隐式转换输入。 但是, explicit 将也有作用,如果构造函数具有多个参数,以及除其中一个参数的默认值为。

请参见

参考

C++关键字

转换