首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >静态成员函数与运行时多态性

静态成员函数与运行时多态性
EN

Stack Overflow用户
提问于 2021-03-02 16:35:13
回答 1查看 217关注 0票数 1
代码语言:javascript
复制
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();  
}

我得到一个编译时错误:

代码语言:javascript
复制
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()构造函数并将其公之于众,则不会出现任何错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-02 23:53:42

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

为了使这种工作正常进行,需要有一个派生()构造函数--要么是定义自己的构造函数,要么是安排默认构造器不出现格式错误的构造函数。您可以通过使Base()公共或保护而不是私有(因此派生()构造函数可以调用它)来实现后者。

所有关于静态成员和虚拟函数的内容都是无关的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66443398

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档