c++ - 使用基类中的函数静态调用纯虚函数的派生类实现

标签 c++ inheritance static pure-virtual

在 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/

相关文章:

c++ - std::string 和 char* 的特化函数模板

python - 在继承类中执行父方法

c# - 重置 System.Timers.Timer 以防止 Elapsed 事件

javascript - 重新加载时 Python Flask 304 响应

Visual Studio 中的 C++ 数组错误

c++ - 这个函数重载是否正确?

c++ - VS2010 C++ 并发运行时 - 如何强制单线程模式?

python - 我怎样才能简单地从现有实例继承方法?

Java动态绑定(bind)调用父类方法

java - 静态类初始化什么时候发生?