静态成员函数和运行时多态性


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();或者删除私有的Base()构造函数并使其成为公共的,我不会得到任何错误。

通过将Base()构造函数设置为私有,Derived()默认构造函数就会变得格式错误(它试图调用私有的Base()),因此会被隐式删除。然后尝试使用它来构造一个Derived,这会给出您所看到的错误。

为了使这个工作,需要有一个派生()构造函数——要么是您自己定义的,要么安排默认构造函数不是病态的。您可以通过将Base()设置为公共或受保护而不是私有(以便派生()构造函数可以调用它)来实现后者。

所有与静态成员和虚函数相关的东西都是不相关的。

最新更新