在 stackoverflow 的其他地方有一些关于这个主题的讨论,但我还没有真正找到我的问题的明确答案。
我的设置是这样的:
class BaseClass
{
virtual short return_number_for_thing1(std::string thing1)=0; //note the pure virtual
virtual short return_number_for_thing2(std::string thing2)=0;
virtual short return_number_for_thing(std::string thing); //virtual is probably not necessary here, I can get rid of it if need be
}
short BaseClass::return_number_for_thing(std::string thing)
{ //pretend thing1 and thing2 are enum'ed somewhere
if (thing == thing1) return return_number_for_thing1(thing);
else if (thing == thing2) return return_number_for_thing2(thing);
}
class DerivedClass1 : BaseClass
{
short return_number_for_thing1(std::string thing1);
short return_number_for_thing2(std::string thing2);
}
class DerivedClass2 : BaseClass
{
short return_number_for_thing1(std::string thing1);
short return_number_for_thing2(std::string thing2);
}
我的问题是,为什么我不能这样写代码:
short number_i_want = DerivedClass2::return_number_for_thing(thing);
我有点理解尝试从 BaseClass 指针调用 return_number_for_thing 没有意义,因为它不知道是调用 DerivedClass1 还是 DerivedClass2 的例程,但如果我给它 DerivedClass2 的范围,应该'它不能弄清楚我想要什么吗?现在,我会在需要时创建 DerivedClass2 或 DerivedClass1 的空白实例,但在我看来我不应该这样做。
最佳答案
在 C++ 中,虚拟和静态不能混用。
virtual
= 具体操作取决于对象的类型。static
= 您不需要对象。
但是,当然可以想象这样的事情。如果 C++ 有元类型之类的东西,允许您将常规类型视为对象,那么它就不会再是一个奇怪的想法了。
伪代码(使用想象的语法):
void f(Class base_class)
{
base_class.StaticMethod();
}
struct Base
{
virtual static StaticMethod(); // impossible in C++
};
struct Derived : Base
{
virtual static StaticMethod(); // impossible in C++
};
f(Base); // impossible in C++
f(Derived); // impossible in C++
创建静态虚函数之类的东西的愿望有时是真正需要的症状(C++ 无法开箱即用):将类型视为对象。
关于c++ - 使用基类中的函数静态调用纯虚函数的派生类实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23431386/