我忘记了为什么基类方法会调用派生的虚拟方法,而该方法的前缀不是this->
或Derived::
类型为对象Derived*
请参阅 Arc::SetAngles(...) 中的注释行:
抽象的:
class Shape {
public:
//...
protected:
//...
virtual void CalculateArea()=0;
virtual void CalculateCenter()=0;
private:
//...
};
根据:
void Arc::CalculateArea() {
_area = 0.5 * _radius * _radius * _theta;
}
void Arc::CalculateCenter() {
double e = GetEndAngle();
double s = GetStartAngle();
double d = e - s;
double x = 0.0;
double y = 0.0;
double offset = 0.0;
if(d < 0.0) {
offset = a2de::A2DE_PI;
}
x = (GetPosition().GetX() + std::cos(((s + e) / 2.0) + offset) * _radius);
y = (GetPosition().GetY() + -std::sin(((s + e) / 2.0) + offset) * _radius);
_center = Vector2D(x, y);
return;
}
void Arc::SetAngles(double startAngle, double endAngle) {
if(startAngle < 0.0) {
startAngle += A2DE_2PI;
}
if(endAngle < 0.0) {
endAngle += A2DE_2PI;
}
_startAngle = std::fmod(startAngle, A2DE_2PI);
_endAngle = std::fmod(endAngle, A2DE_2PI);
//must call base version explicitly otherwise Sector:: versions are called when object is of type Sector* regardless if prefaced with this-> or nothing.
Arc::CalculateCenter();
Arc::CalculateLength();
Arc::CalculateArea();
}
衍生的:
void Sector::CalculateArea() {
_area = (_radius * _radius * _theta) / 2.0;
}
void Sector::CalculateCenter() {
double x = (4 * _radius) / (3 * a2de::A2DE_PI);
x += this->GetX();
_center = Vector2D(x, GetY());
}
void Sector::SetAngles(double startAngle, double endAngle) {
Arc::SetAngles(startAngle, endAngle);
Sector::CalculateArea();
Sector::CalculateCenter();
}