【发布时间】:2017-09-03 08:04:19
【问题描述】:
我已经实现了从抽象类派生的不同类,每个类都有不同的方法。问题是我必须在运行时声明对象,所以我必须创建一个指向基类的指针,我不能使用每个派生类的方法。
我创建了一个示例来更好地解释我的意思:
#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”类的方法。
具有这种逻辑的程序的正确实现是什么?
【问题讨论】:
-
那么不要为运行时多态性而烦恼。根据用户输入调用不同的函数。
标签: c++ class oop methods abstract-class