请大伙看看一个vector<基类> 成员访问派生类成员的问题?
请大伙帮忙看一下一个关于vector<基类>成员访问派生类成员以及输出的问题。
我有以下类层次:
class CAtom
{
public:
virtual ~CAtom( ) { }
virtual int EncodedLength( ) = 0;
virtual int Length( ) = 0;
virtual string toString( ) = 0;
};
class CAtomInt : public CAtom
{
public:
CAtomInt( );
virtual ~CAtomInt( );
int getValue( ) const;
void setValue( int iInt );
private:
int m_iInt;
};
class CAtomString : public CAtom
{
public:
CAtomString( );
virtual ~CAtomString( );
string getValue( ) const;
void setValue( string strString );
private:
string m_strString;
};
class CAtomList : public CAtom
{
public:
CAtomList( );
virtual ~CAtomList( );
vector<CAtom *> getValue( ) const;
vector<CAtom *> *getValuePtr( ) const;
void setValue( vector<CAtom *> vecList );
private:
vector<CAtom *> m_vecList;
};
CAtomList 类中的数据成员m_vecList存放的有可能是CAtomInt 类型的指针,也有可能是CAtomString 类型的指针,那我如何设计以上这些类,才可以正确输出m_vecList的内容。可以的话,请劳你写几句代码吧。我试过在基类CAtom写一个输出的虚函数,在CAtomInt, CAtomString,CAtomList也写上各自的实现,但好像不行。
代码如下:
CAtomList *cal1 = new CAtomList;
const char *pcFile = "a.torrent";
cal1 = (CAtomList *)DecodeFile(pcFile);
cout << cal1->isList() << endl;
vector<CAtom *>::iterator it;
for (it = cal1->getValuePtr()->begin(); it < cal1->getValuePtr()->end(); it++)
{
cout << ((CAtom *)(it))->getValue() << endl;
}
以上这段代码请问有什么错啊?这个问题困扰了我一天了,看了很多书也没啥主意,再大家帮帮我~~~ ,不甚感激!!!谢谢谢谢!!!