给出以下代码:
(这主要是关于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上做这件事的方式是最好/最有效的方式吗?我觉得有更好的方法可以做到这一点,但我不知道怎么做。
答案 0 :(得分:2)
答案是您不这样做,它完全由多态处理,请阅读以下代码:
并尝试将其映射到您的代码:
#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;
}
答案 1 :(得分:0)
这足以满足您的需求:
DerivedA& temp = static_cast<DerivedA&>(base);
temp.FunctionA();
内幕下,这与您刚进行的C样式强制转换相同,但将其显式表示是一种很好的做法。