请考虑以下代码:
#include <iostream>
#include <string>
enum Type { T1, T2 };
class Base {
public:
std::string baseName;
Type type;
Base(const std::string& bn, Type t):
baseName(bn), type(t) {}
};
class Derived1 : public Base
{
public:
std::string dName;
int x = 10;
Derived1(const std::string& bn, const std::string& dn):
Base(bn, Type::T1), dName("Dervied1"+dn) {}
int getX(void) const { return x; }
};
class Derived2 : public Base
{
public:
std::string dName;
int y = 20;
Derived2(const std::string& bn, const std::string& dn):
Base(bn, Type::T2), dName("Derived2"+dn){}
int getY(void) const { return y; }
};
void func(Base& b)
{
if (b.type == Type::T1)
{
Derived1& d1 = static_cast<Derived1&>(b);
std::cout << d1.baseName << " " << d1.dName << " " << d1.getX();
std::cout << std::endl;
}
else
{
Derived2& d2 = static_cast<Derived2&>(b);
std::cout << d2.baseName << " " << d2.dName << " " << d2.getY();
}
};
int main(void)
{
Derived1 d1("Base", "foo");
func(d1);
Derived2 d2("Base", "foo");
func(d2);
}
要求是有一个函数可以接受基类值,然后根据派生实例的“类型”,做一些不同的事情 . 我的问题是 - 这是正确的做事方式,还是我错过了一些重要的设计模式 . 我记得读过使用static_cast或dynamic_cast意味着设计本身存在一些错误 . 我理解,理想情况下,基类可以具有派生类实现的虚函数,并且在运行时它们可以进行多态调度 . 但是,在这种情况下,每个派生类中有两个特定于这些类的函数,即 . getX和getY . 如何更改设计以使其更好,也许不使用演员?
谢谢!
2 回答
这正是多态性的全部意义所在 . 但是你没有按照它的使用方式使用它 .
没有 .
通过完全删除
Type
并在Base
中引入虚拟方法可以更好地处理这个问题 .究竟 .
所以?正确使用多态不会阻止这种情况 .
正确使用多态性 . 例如:
然后通过移动公共代码使其更进一步,以便派生类可以共享它:
如果您可以选择使用
virtual
成员函数,如the other answer所述,则这是最佳使用方法 . 但是,有些情况下你没有那么奢侈 . 在这种情况下,您可以根据派生类型的类型构建调度机制 .运行上述程序的输出: