【发布时间】:2020-11-16 21:41:44
【问题描述】:
我有一个程序,其中有一个指向基类的指针向量,其中存储了多个不同派生类的实例。所有这些对象根据它们的类型以不同的方式相互交互,我想以一种智能的方式实现这些交互。我希望有一个中介类来尽可能多地保留与这些交互相关的代码。
这是我想要实现的简化版本:
#include <iostream>
#include <vector>
class Gesture {};
class Rock : public Gesture {};
class Paper : public Gesture {};
class Scissors : public Gesture {};
class Game {
public:
static void play(Rock* first, Rock* second) {
std::cout << "Rock ties with rock." << std::endl;
}
static void play(Rock* first, Paper* second) {
std::cout << "Rock is beaten by paper." << std::endl;
}
static void play(Rock* first, Scissors* second) {
std::cout << "Rock beats scissors." << std::endl;
}
static void play(Paper* first, Rock* second) {
std::cout << "Paper beats rock." << std::endl;
}
static void play(Paper* first, Paper* second) {
std::cout << "Paper ties with paper." << std::endl;
}
static void play(Paper* first, Scissors* second) {
std::cout << "Paper is beaten by scissors." << std::endl;
}
static void play(Scissors* first, Rock* second) {
std::cout << "Scissors are beaten by rock." << std::endl;
}
static void play(Scissors* first, Paper* second) {
std::cout << "Scissors beat paper." << std::endl;
}
static void play(Scissors* first, Scissors* second) {
std::cout << "Scissors tie with scissors." << std::endl;
}
};
int main()
{
Rock rock;
Paper paper;
Scissors scissors;
std::vector<Gesture*> gestures;
gestures.push_back(&rock);
gestures.push_back(&paper);
gestures.push_back(&scissors);
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 3; ++j) {
// alas, downcasting doesn't happen automagically...
Game::play(gestures[i], gestures[j]);
}
}
return 0;
}
有没有一种简单的方法来实现向下转换,而无需编译时知道哪些派生类有问题?这个问题的公认答案:Polymorphism and get object type in C++ 似乎解决了我的问题,但我想知道是否可以避免更改派生类(如果可能,我想将相关代码收集到中介类中)。我想我可以通过 switch 语句找出派生类,该语句尝试向下转换到所有可能的派生类,并检查哪个不返回 nullptr,但这似乎不是特别“聪明”。
有什么想法吗?
【问题讨论】:
标签: c++ inheritance downcast mediator