c – 应用于运算符而不是构造函数的显式关键字

前端之家收集整理的这篇文章主要介绍了c – 应用于运算符而不是构造函数的显式关键字前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的课程中,

为什么要让运算符明确.我认为明确是为了防止对构造函数的隐式调用

class Content
            {
public:

 virtual ~Content() = 0;
 virtual explicit operator float&();
 virtual explicit operator long long&();
 virtual explicit operator std::string&()
}

解决方法

I thought that explicit was to prevent implicit calling of
constructors?

从C 11开始,它也适用于user-defined conversions(也就是演员操作符).

Why would you make the operators explicit

在此上下文中使用,explicit关键字使转换仅适用于直接初始化和显式转换.见[class.conv.fct¶2]

A conversion function may be explicit ([dcl.fct.spec]),in which case
it is only considered as a user-defined conversion for
direct-initialization
([dcl.init]). Otherwise,user-defined
conversions are not restricted to use in assignments and
initializations.

这有助于您确保编译器不会针对您的意图尝试转换,因此您必须自己明确地进行转换,从而减少出错的空间.例:

struct Foo
{
    explicit operator int() {return 0;}
    operator int*() {return nullptr;}
};

int main()
{
    Foo foo;

    //int xi = foo; // Error,conversion must be explicit
    int i = static_cast<int>(foo); // OK,conversion is explicit
    int* i_ptr = foo; // OK,implicit conversion to `int*` is allowed

    int i_direct(foo); // OK,direct initialization allowed
    int* i_ptr_direct(foo); // OK,direct initialization after implicit conversion

    return 0;
}

它还可以帮助解决多个转换选项适用的情况下的歧义,使编译器没有标准来决定选择哪一个:

struct Bar
{
    operator int() {return 1;}
    operator char() {return '1';}
};

int main()
{
    Bar bar;    
    //double d = bar; // Error,implicit conversion is ambiguous    
    return 0;
}

添加明确:

struct Bar
{
    operator int() {return 1;}
    explicit operator char() {return '1';}
};

int main()
{
    Bar bar;    
    double d = bar; // OK,implicit conversion to `int` is the only option    
    return 0;
}
原文链接:https://www.f2er.com/c/239530.html

猜你在找的C&C++相关文章