c++ - 调用不属于基类的派生类函数的最佳方法是什么?

标签 c++

给定以下代码:
(这主要是关于 Function() 方法中发生的事情,其余只是设置/上下文。)

enum class class_type { a, b };

class Base {
   public:
    Base(class_type type) : type(type) {}

    class_type type;
};

class DerivedA : public Base {
   public:
    DerivedA() : Base(class_type::a) {}

    void FunctionA() {}
};

class DerivedB : public Base {
   public:
    DerivedB() : Base(class_type::b) {}

    void FunctionB() {}
};

void Function(Base& base) {
    switch (base.type) {
        case class_type::a: {
            DerivedA& temp = (DerivedA&)base; // Is this the best way?
            temp.FunctionA();
            break;
        }
        case class_type::b: {
            base.FunctionB(); // This obviously doesn't work.
            break;
        }
    }
}

int main() {
    DerivedA derived_class;
    Function(derived_class);
}

我在这里使用 DerivedA 的方式是最好/最有效的方式吗?我觉得有更好的方法可以做到这一点,但我不知道怎么做。

最佳答案

答案是你不要那样做,它完全由多态处理,阅读这段代码:

并尝试将其映射到您的代码:

  • Shap 是您的基地
  • Rectangle 是您的 DerivedA
  • Triangle 是您的 DerivedB
#include <iostream> 
using namespace std;

class Shape {
   protected:
      int width, height;

   public:
      Shape( int a = 0, int b = 0){
         width = a;
         height = b;
      }
      int area() {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};
class Rectangle: public Shape {
   public:
      Rectangle( int a = 0, int b = 0):Shape(a, b) { }

      int area () { 
         cout << "Rectangle class area :" <<endl;
         return (width * height); 
      }
};

class Triangle: public Shape {
   public:
      Triangle( int a = 0, int b = 0):Shape(a, b) { }

      int area () { 
         cout << "Triangle class area :" <<endl;
         return (width * height / 2); 
      }
};

// Main function for the program
int main() {
   Shape *shape;
   Rectangle rec(10,7);
   Triangle  tri(10,5);

   // store the address of Rectangle
   shape = &rec;

   // call rectangle area.
   shape->area();

   // store the address of Triangle
   shape = &tri;

   // call triangle area.
   shape->area();

   return 0;
}

关于c++ - 调用不属于基类的派生类函数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57016628/

相关文章:

c++ - 将指针传递给宏的省时方法

c++ - 根据 Qt 版本添加条件宏

c++ - 如何将CEdit类型的数据转换为CString类型的数据以及如何将其显示在消息框中?

c++ - 在这种情况下如何释放内存?

c++ - 如何在 C/C++ 中对多维数组进行排序

c++ - 如何杀死旧的父进程?

c++ - 奇怪的链接器错误

c++ - 谷歌测试不处理异常

c++ - 如何更新对象的属性?

c++ - C++ 中的“助手”函数