微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决静态成员函数和运行时多态性

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;
      |     ^~~~

Live Example

在 Base::get 函数中,如果我执行 Base* b = new Base();或者删除私有 Base() 构造函数并将其公开,我没有收到任何错误

解决方法

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

为了完成这项工作,需要有一个 Derived() 构造函数——要么是你自己定义的,要么是安排默认的构造函数没有格式错误。您可以通过将 Base() 设为 public 或 protected 而不是私有来实现后者(因此 Derived() 构造函数可以调用它)。

静态成员和虚函数的所有内容都无关紧要。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。