- 论坛徽章:
- 0
|
刚看了<<c++ templates:the complete guide>>的第14.1节发现了例子可能有问题
// poly/dynahier.hpp
#include "coord.hpp"
// common abstract base class GeoObj for geometric objects
class GeoObj {
public:
// draw geometric object:
virtual void draw() const = 0;
// return center of gravity of geometric object:
virtual Coord center_of_gravity() const = 0;
…
};
// concrete geometric object class Circle
// - derived from GeoObj
class Circle : public GeoObj {
public:
virtual void draw() const;
virtual Coord center_of_gravity() const;
…
};
// concrete geometric object class Line
// - derived from GeoObj
class Line : public GeoObj {
public:
virtual void draw() const;
virtual Coord center_of_gravity() const;
…
};
…
// poly/dynapoly.cpp
#include "dynahier.hpp"
#include <vector>
// draw any GeoObj
void myDraw (GeoObj const& obj)
{
obj.draw(); // call draw() according to type of object
}
// process distance of center of gravity between two GeoObjs
Coord distance (GeoObj const& x1, GeoObj const& x2)
{
Coord c = x1.center_of_gravity() - x2.center_of_gravity();
return c.abs(); // return coordinates as absolute values
}
// draw inhomogeneous collection of GeoObjs
void drawElems (std::vector<GeoObj*> const& elems)
{
for (unsigned i=0; i<elems.size(); ++i) {
elems->draw(); // call draw() according to type of element
}
}
int main()
{
Line l;
Circle c, c1, c2;
myDraw(l); // myDraw(GeoObj&) => Line::draw()
myDraw(c); // myDraw(GeoObj&) => Circle::draw()
distance(c1,c2); // distance(GeoObj&,GeoObj&)
distance(l,c); // distance(GeoObj&,GeoObj&)
std::vector<GeoObj*> coll; // inhomogeneous collection
coll.push_back(&l); // insert line
coll.push_back(&c); // insert circle
drawElems(coll); // draw different kinds of GeoObjs
}
我的疑问是 1:vector容器可以同时接受不同类型对象指针吗?
2:这个问题基于上一个问题,vector容器怎么去确定不同的容器元素的大小?我的意思是怎么光用elems中的i就把不同类型的对象分隔开,上面的例子可能是个特例,两个类(Circle,line)都没实质性的data在里头,所以elems的长度比较容易确搞定(也就是说两个类的对象占内存的大小是相同的)
最后说几句,如果我的第2个想法是对的,那么这个例子代码就是忽悠人的,简直是害人,希望得到各位高人的指导,thx
[ 本帖最后由 vividone 于 2008-5-3 08:43 编辑 ] |
|