【发布时间】: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;
| ^~~~
在 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