【问题标题】:Static member function and run time polymorphism静态成员函数和运行时多态性
【发布时间】:2021-03-02 16:35:13
【问题描述】:
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* b = new Derived(); 定义了一个名为 b 的全新变量,它不同于 Base::b
  • 可能是因为Derived 没有定义?这不是一个完整的例子,是吗?
  • 注意这里的内存泄漏,如果你调用get 两次你会创建两个Derived 实例并泄漏它们。
  • 错误信息告诉你所有你需要知道的——如果你知道如何阅读它们。您无法创建Derived,因为它的构造函数(在这种情况下由编译器生成,但如果您定义一个,则相同)需要调用其父类的构造函数——但那是private。任何 private 都不能在其外部引用——即使是派生类。如果你不能做到public,请尝试声明它protected

标签: c++ c++11 static-members


【解决方案1】:

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

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

所有与静态成员和虚函数无关的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多