c++ - 为什么 `explicit` 与 `virtual` 不兼容?

标签 c++ function c++11 virtual explicit

struct A
{
    // error C2216: 'explicit' cannot be used with 'virtual'
    virtual explicit operator bool() const 
    {
        return true;
    }
};

struct B : A
{
    // error C2216: 'explicit' cannot be used with 'override'
    explicit operator bool() const override 
    {
        return false;
    }
};

int main()
{
    if (A())
    {}

    if (B())
    {}
}

我的编译器是 VC++ 2013 RC。

为什么explicitvirtual不兼容?

原因是什么?

最佳答案

看起来像一个错误,因为以下引用证明它们确实兼容,我找不到任何禁止它的内容。

12.3.2 转换函数[class.conv.fct]

2) A conversion function may be explicit [...]
[...]
5) Conversion functions can be virtual.

7.1.2 函数说明符[dcl.fct.spec]

5) The virtual specifier shall be used only in the initial declaration of a non-static class member function; see 10.3.
6) The explicit specifier shall be used only in the declaration of a constructor or conversion function within its class definition; see 12.3.1 and 12.3.2.

关于c++ - 为什么 `explicit` 与 `virtual` 不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19356232/

相关文章:

c++ - "multiple overloads"使用具有重复类型的模板类

c++ - 编译器对带有元组参数的函数的混淆

c++ - 是否可以从 qt QColumnView 中删除预览小部件?

python - 如何随机化您名字和姓氏的首字母

c - 为什么 fputs() 需要一个常量作为第一个参数而不是 fputc()?

c++ - 通过引用将整数类型的变量传递给函数会比通过值更有效吗?

c++ - char16_t 字符串必须使用 UTF-16 编码吗?

c++ - 程序输出问题

c++ - 找不到可执行文件,请指定一个

c++ - 依赖溢出有危险吗?