我实现了从抽象类派生的不同类,每个类都有不同的方法。问题是我必须只在运行时声明对象,所以我必须创建一个指向基类的指针,我不能使用每个派生类的方法。
我创建了一个示例来更好地解释我的意思:
#include <iostream>
using namespace std;
class poligon
{
public:
double h, l;
void setPoligon(double h, double l) {
this->h = h;
this->l = l;
}
virtual double GetArea() = 0;
virtual void GetType() = 0;
};
class triangle : public poligon
{
double GetArea() { return l*h / 2; }
void GetType() { cout << "triangle" << endl; }
double GetDiag() { return sqrt(l*l + h*h); }
};
class rectangle : public poligon
{
double GetArea() { return l*h; }
void GetType() { cout << "rectangle" << endl; }
};
void main()
{
poligon* X;
int input;
cout << "1 for triangle and 2 for rectangle: ";
cin >> input;
if (input == 1)
{
X = new triangle;
}
else if (input == 2)
{
X = new rectangle;
}
else
{
cout << "Error";
}
X->h = 5;
X->l = 6;
X->GetType();
cout << "Area = " << X->GetArea() << endl;
if (input == 2)
{
cout << "Diangonal = " << X->GetDiag() << endl; // NOT POSSIBLE BECAUSE " GetDiag()" IS NOT A METHOD OF "poligon" CLASS !!!
}
}
显然不能使用 main 末尾的方法 X->GetDiag()
,因为它不是“poligon”类的方法。
哪个是具有这种逻辑的程序的正确实现?
最佳答案
在基类中引入一个方法
virtual bool boHasDiagonal(void) =0;
在基类中无条件声明:
virtual double GetDiag();
在两个派生类中以不同的方式实现它:
virtual bool boHasDiagonal(void) {return true;} // rectangle
virtual bool boHasDiagonal(void) {return false;} // triangle
改变输出行:
if (X->boHasDiagonal())
{cout << "Diangonal = " << X->GetDiag() << endl;}
为了避免偏执(在我看来,这是程序员的健康心态),请使用 Gluttton 提出的 GetDiag()
默认实现的概念,它会发出错误信号(如他在这里的回答)。
对于许多 poligons 的情况,我喜欢评论中 Rakete1111 的提议。
关于c++ - 如何使用不同的方法实现从抽象派生的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46021440/