【发布时间】:2011-05-24 18:33:48
【问题描述】:
我有一个 Visual Studio 2008 C++ 应用程序,其中包含从一个公共基础派生的几种类型的对象。例如:
class Base
{
public:
std::string Time() const { /*return formatted time*/; };
private:
SYSTEMTIME time_;
};
class Foo : public Base
{
public:
const char* FooFunc() const { return "Hello from foo!"; };
};
typedef std::vector< Base > BaseList;
class Bar : public Base
{
public:
const char* BarFunc() const { return "Hello from bar!"; };
void push_back( const Base& obj ) { list_.push_back( obj ); };
BaseList::const_iterator begin() const { return list_.begin(); };
BaseList::const_iterator end() const { return list_.end(); };
private:
BaseList list_;
};
这些对象存储在std::vector< Base > 中。我需要输出每个Foo 和Bar 类中的信息以及存储在基础中的信息。 但是,我想避免 RTTI。
int main( int, char** )
{
BaseList list;
Foo foo;
Bar bar;
Foo foo2;
list.push_back( foo );
list.push_back( bar );
bar.push_back( foo2 );
for( BaseList::const_iterator it = list.begin();
it != list.end();
++it )
{
printf( "%s ", it->Time() );
// print Foo information for objects of type Foo
// OR print Bar information for objects of type Bar.
// Descend in to objects of type Bar to print its children.
}
return 0;
}
在这种情况下,所需的输出将是:
11:13:05 Hello from foo!
11:22:14 Hello from bar!
11:26:04 Hello from foo!
我可以对此设计进行哪些更改,以避免使用 RTTI 作为解决方案,但仍允许我在嵌套树状结构中存储具有不同功能的对象,如 Foo 和 Bar?
谢谢, 保罗H
【问题讨论】:
-
@Fred:我正要回答它,说你做了什么。将您的评论转换为答案,其他人会更容易看到它。
-
只是好奇:为什么要避免 RTTI?
标签: c++ data-structures