一个子类的两个派生类,但具有两个返回类型

two derived class of a subclass but with two return type

本文关键字:两个 返回类型 一个 派生 子类      更新时间:2024-04-28

我有一个超类(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();
};

我愿意用超类指针调用子类函数

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

这正是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.