class Base
{
private:
Base() = default;
static Base *b;
public:
static Base* get();
};
class Derived: public Base
{
};
Base* Base::b=nullptr;
Base* Base::get(){Base* b = new Derived();return b;}
void main()
{
Base* b = Base::get();
}我得到一个编译时错误:
main.cpp: In static member function 'static Base* Base::get()':
main.cpp:14:41: error: use of deleted function 'Derived::Derived()'
14 | Base* Base::get(){Base* b = new Derived();return b;}
| ^
main.cpp:9:7: note: 'Derived::Derived()' is implicitly deleted because the default definition would be ill-formed:
9 | class Derived: public Base
| ^~~~~~~
main.cpp:9:7: error: 'constexpr Base::Base()' is private within this context
main.cpp:4:5: note: declared private here
4 | Base() = default;
| ^~~~在Base::get函数中,如果我执行Base* b= new ();或删除私有Base()构造函数并将其公之于众,则不会出现任何错误。
发布于 2021-03-02 23:53:42
通过将Base()构造函数设置为私有,派生()默认构造函数将变成格式错误(它试图调用私有Base()),因此被隐式删除。然后尝试使用它来构造派生的,这将给出您所看到的错误。
为了使这种工作正常进行,需要有一个派生()构造函数--要么是定义自己的构造函数,要么是安排默认构造器不出现格式错误的构造函数。您可以通过使Base()公共或保护而不是私有(因此派生()构造函数可以调用它)来实现后者。
所有关于静态成员和虚拟函数的内容都是无关的。
https://stackoverflow.com/questions/66443398
复制相似问题