静态成员函数和运行时间多态
Static member function and run time polymorphism
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() 构造函数并使其成为 public,我没有收到任何错误。
通过将 Base() 构造函数设为私有,Derived() 默认构造函数变得格式错误(它试图调用私有 Base()),因此被隐式删除。然后您尝试使用它来构造一个 Derived,这会给出您看到的错误。
为了使这项工作正常进行,需要有一个 Derived() 构造函数——您可以自己定义一个构造函数,也可以安排默认构造函数不存在错误格式。您可以通过使 Base() public 或 protected 而不是 private 来实现后者(因此 Derived() 构造函数可以调用它)。
所有与静态成员和虚函数无关的东西。
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() 构造函数并使其成为 public,我没有收到任何错误。
通过将 Base() 构造函数设为私有,Derived() 默认构造函数变得格式错误(它试图调用私有 Base()),因此被隐式删除。然后您尝试使用它来构造一个 Derived,这会给出您看到的错误。
为了使这项工作正常进行,需要有一个 Derived() 构造函数——您可以自己定义一个构造函数,也可以安排默认构造函数不存在错误格式。您可以通过使 Base() public 或 protected 而不是 private 来实现后者(因此 Derived() 构造函数可以调用它)。
所有与静态成员和虚函数无关的东西。