如何使用抽象基类直接初始化派生类?

huangapple go评论61阅读模式
英文:

How to direct-initialize a derived class with an abstract base?

问题

Without the virtual method, the make_unique line in main compiles ok. But I'm lost as to how to direct-initialize a Derived like this when it's there. Is this possible?

struct Base
{
	virtual void method();
};
struct Derived : public Base
{
	int i;
};

int main() {
    Base base{}; // this works
    make_unique<Derived>(Base{}, 3); // this doesn't compile unless the virtual method is removed
}

I don't see any mention of virtual methods in the "Direct initialization" page: https://en.cppreference.com/w/cpp/language/direct_initialization

英文:

Without the virtual method, the make_unique line in main compiles ok. But I'm lost as to how to direct-initialize a Derived like this when it's there. Is this possible?

struct Base
{
	virtual void method();
};
struct Derived : public Base
{
	int i;
};

int main() {
    Base base{}; // this works
	make_unique&lt;Derived&gt;(Base{}, 3); // this doesn&#39;t compile unless the virtual method is removed
}

I don't see any mention of virtual methods in the "Direct initilization" page: https://en.cppreference.com/w/cpp/language/direct_initialization

答案1

得分: 6

使用virtual方法后,您的Derived类不再是一个聚合,因此无法进行这种形式的初始化。

来自cppreference

聚合可以是以下类型之一:

  • 数组类型
  • 类类型(通常为structunion),具有
    • 无用户声明的构造函数
      (直到C++11)
    • 无用户提供、继承或显式的构造函数
      (自C++11以来)
      (直到C++20)
    • 无用户声明或继承的构造函数
      (自C++20以来)
    • 无私有或受保护的[直接(自C++17以来)]非静态数据成员
    • 无基类
      (直到C++17)
    • 无虚基类(自C++17以来)
    • 无私有或受保护的直接基类
      (自C++17以来)
    • 无虚成员函数
    • 无默认成员初始化项
      (自C++11以来)
      (直到C++14)
英文:

With the virtual method, your Derived class is not an aggregate anymore, so this form of initialization can't be done.

From cppreference:

An aggregate is one of the following types:

  • array type
  • class type (typically, struct or union), that has
    • no user-declared constructors
      (until C++11)
    • no user-provided, inherited, or explicit constructors
      (since C++11)
      (until C++20)
    • no user-declared or inherited constructors
      (since C++20)
    • no private or protected [direct (since C++17)] non-static data members
    • no base classes
      (until C++17)
    • no virtual base classes (since C++17)
    • no private or protected direct base classes
      (since C++17)
    • no virtual member functions
    • no default member initializers
      (since C++11)
      (until C++14)

huangapple
  • 本文由 发表于 2023年6月1日 04:23:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定