【发布时间】:2014-10-16 08:53:02
【问题描述】:
我对 C++ 中接口类的使用有疑问,但不知道它的名称以及如何搜索它。希望你能帮助我,好心。
我将尝试用一个简单的例子来说明我的问题。
我有 5 种不同的可能对象,例如 三角形、正方形、矩形、五边形和六边形。
所有这些对象都有共同的属性,所以我将有一个接口类Shape。
现在,我想要的是:我将拥有一个 Shape 类对象,并且由于运行时的选择,我希望能够将其用作其他 5 个对象之一。
所以我做了如下的事情:
class Shape
{
public:
virtual int getArea()=0;
virtual void setWidth(int w)
{
width = w;
}
virtual void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
class Triangle: public Shape
{
public:
int getArea()
{
return (m_Width * m_Height)/2;
}
};
class Rectangle: public Shape
{
public:
int getArea()
{
return (m_Width * m_Height);
}
};
使用时,我只想创建一个 Shape 的对象,并用其中一个派生类对其进行初始化。所以,从那时起,我希望它表现得像这样的对象的一个实例:
void main(){
Shape* shape;
std::string shapeType;
std::cout<<"Enter Shape Type: triangle or rectangle."<<std::endl;
std::cin>>shapeType;
if (shapeType == "triangle")
shape = new Triangle();
else if (shapeType == "rectangle")
shape = new Rectangle();
shape->setWidth(5);
shape->setHeight(7);
std::cout<<shape->getArea()<<std::endl;
}
到这里没问题。问题从这里开始。这些派生类可能有不同的属性、方法。当我将这些方法添加到它们自己的类时,shape 对象无法访问它(正确)。可以使用的另一种方法是将新的派生对象转换为 shape 对象,例如:
Triangle* triangle = (Triangle*)shape;
// now I can access own attributes of Triangle object.
但这并不是你想的那样处理它的好方法。除此之外,我只知道一种方法迫使我将所有这些属性写入 Shape 类并在所需的派生类中实现它们,如果不需要其他类,则将其实现为空。
你有什么好的办法解决这个问题吗?我相信会有,但我对这个主题没有太多经验,所以希望你有一个适合我想要的解决方案。
提前致谢。
【问题讨论】:
-
这个问题没有好的解决办法。你可以用大部分无用的虚函数填充你的基类,或者使用 dynamic_cast hacks、标记的联合、访问者模式……所有这些都是坏的。选择你的毒药。
-
不要忘记虚拟析构函数。
标签: c++ interface polymorphism abstract-class