【发布时间】:2014-04-30 09:36:45
【问题描述】:
我正在研究抽象类的东西。
#include <iostream>
#include <vector>
using namespace std;
class Shape
{
protected:
int m_size;
public:
int getSize() { return m_size; }
virtual bool isEqual(Shape *rhs) = 0;
};
这是派生类之一:
class Circle : public Shape
{
public:
Circle(int size) { m_size = size; }
bool isEqual(Shape *rhs)
{
Circle* circle = dynamic_cast<Circle*>(rhs);
if(circle == 0)
return false; // not a Circle
return m_size == circle->getSize();
}
};
我将所有形状存储在一个容器中(基本上是形状指针的向量。
class Container
{
private:
vector<Shape*> v;
public:
~Container()
{
for(int i = 0; i < v.size(); i++) {
cout << "Removind element Nr. " << i << endl;
delete v[i];
}
v.erase(v.begin(), v.end());
}
bool add(Shape *shape)
{
for(int i = 0; i < v.size(); i++) {
if( v[i] == shape ) {
return false;
}
if( v[i]->isEqual(shape) ) {
return false;
}
}
v.push_back(shape);
return true;
}
};
我想知道是否可以在容器中添加元素而不将它们作为指针传递。 目前它是这样工作的:
Container c;
c.add(new Circle(10));
我想以这种方式使用它:
C.add(Circle(10));
解决办法是什么?
【问题讨论】:
-
顺便说一句,缺少虚拟析构函数。
-
需要虚拟析构函数吗?
-
@bandara:添加它几乎是免费的,并且它避免了 memleak(一旦你在子类中有析构函数)......
标签: c++ polymorphism clone virtual