英文:
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<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 initilization" page: https://en.cppreference.com/w/cpp/language/direct_initialization
答案1
得分: 6
使用virtual
方法后,您的Derived
类不再是一个聚合,因此无法进行这种形式的初始化。
来自cppreference:
聚合可以是以下类型之一:
- 数组类型
- 类类型(通常为
struct
或union
),具有- 无用户声明的构造函数
(直到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
orunion
), 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)
- no user-declared constructors
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论