通过初始化器列表实例化抽象类 [英] Instantiation of an abstract class via initializer list

查看:122
本文介绍了通过初始化器列表实例化抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解为什么编译器允许以下代码编译

  #include< iostream> 

struct A
{
A()
{
std :: cout< A :: A\\\
;
}

virtual void f()const = 0;
};

void g(const A& a)
{
a.f();
}

int main()
{
g({});
}

它甚至会输出 A :: A

如果我用替换 g({}) g(A())它显然不编译。它抱怨 A 是抽象的,不能被实例化。 Clang和GCC都编译这个罚款,没有任何警告。当运行这两个版本时,打印纯虚拟方法并终止。

解决方案

这看起来像是已知的 g ++错误号70939



$ b b
$ b

  class A {
public:
A(){
printf(A()\\\
);
}
virtual void b()const = 0;
};
int main(){
const A&一个{};
a.b();
return 0;
}


  const A&作为 g({})  



< $ c>调用。


I would like to understand why the compiler allows the following code to compile

#include <iostream>

struct A
{
    A()
    {
        std::cout << "A::A\n";
    }

    virtual void f() const = 0;
};

void g(const A& a)
{
    a.f();
}

int main()
{
    g({});
}

It even outputs A::A when run.

If I replace g({}) with g(A()) it obviously doesn't compile. It complains that A is abstract and cannot be instantiated. Both Clang and GCC compile this fine without any warnings. When run both versions print pure virtual method called and terminate.

解决方案

This looks like a known g++ bug number 70939:

creating object of abstract class allowed in all versions of g++

g++ compiles ill formed C++ program successfully

class A {
public:
    A() {
        printf("A()\n");
    }
    virtual void b() const = 0;
};
int main() {
    const A& a{};
    a.b();
    return 0;
}

Your code does the same thing as this line

const A& a{}

as part of g({}) invocation.

这篇关于通过初始化器列表实例化抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆