首页 > 解决方案 > 子类的两个派生类,但有两个返回类型

问题描述

我有一个超类(A)和两个子类(B,C)

A 中的抽象函数在 B 和 C 中有两种不同的返回类型!

我如何声明这些?

返回类型很重要

class A {                              //Super Class
public:
  A();
  virtual (some Type) QWERTY() = 0;
};

class B : public A {                   //Sub Class
public:
  B();
  double QWERTY();
};

class C : public A {                   //Sub Class
public:
  C();
  unsigned int QWERTY();
};

标签: c++polymorphismabstract-class

解决方案


我要用超类指针调用子类函数

由于每个子类中的函数不同,因此您必须从指向这些子类的指针访问它们。

这正是dynamic_cast<>可以提供帮助的情况:当且仅当它恰好是正确的类型时,它可以有条件地将指针从基类转换为子类:

void foo(A* a_ptr) {
  B* b_ptr = dynamic_cast<B*>(a_ptr);
  C* c_ptr = dynamic_cast<C*>(a_ptr);

  if(b_ptr) {
    b_ptr->QWERTY();
  }

  if(c_ptr) {
    c_ptr->QWERTY();
  }
}

It's, however, worth mentioning that this is some pretty ugly code, and might be suitable to solve the quiz you are presenting us, but in a normal environment, there are some design reevaluation that would happen before going to implement things this way.

推荐阅读