给定以下代码:
(这主要是关于 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/