当前位置: 首页 > 图文教程 > 开发语言 > VC++ > 再谈“在STL列表(Lists)中插入不同类型的对象”

VC++
使用免费界面换肤软件 USkin
Cell插件在J2EE系统中的应用
采用MFC编制MVC模式之球体演示程序
托管资源全攻略
使用 MFC 编写打印程序
根据所选择的 TrueType 字体生成点阵数据
让你的软件界面更漂亮(四):不完美之菜单
VC界面的实现
让你的软件界面更漂亮(三)
分割窗口后如何限制分割条的移动范围
关于 CFileDialog 对话框多选功能的一个问题
让你的软件界面更漂亮(二)
对话框模板,RegexTest
让你的软件界面更漂亮(一)
利用窗口子类化隐藏系统图标
KVIP考勤系统
类似于FlashGet的悬浮框的制作
计算MDI子窗口数,仅显示文件夹的打开对话框
智能ABC窗口的实现
在打开文件对话框上实现图象预览

VC++ 中的 再谈“在STL列表(Lists)中插入不同类型的对象”


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-30   浏览: 76 ::
收藏到网摘: n/a

再谈“在STL列表(Lists)中插入不同类型的对象”


作者:周公建



    看到贵网站上的一篇文章:“在STL列表(Lists)中插入不同类型的对象”。我觉得该文回答还没有指出问题的本质,所以本人提出我的观点,恳请指正。本人认为,错误产生的原因在于指针转化过程中,程序没有指出该指针最初的原型,或者说,由于未找到正确的子类函数地址才发生调用错误的,本人原代码如下:用Dev-cpp的g++编译通过。
#include<iostream>#include<algorithm>#include <vector>#include <string>/** * 父类:synObject */class synObject { public :	synObject();	string GetClass();	string className;};synObject::synObject(){	className = "synObject";}string synObject::GetClass(){	return className;}/** * 子类1:synPin */ class synPin : public synObject {	string pin;public :	synPin();	void SetPin(string Pin);	string GetPin();private:};synPin::synPin(){	className = "synPin";}void synPin::SetPin(string Pin){	pin = Pin;}string synPin::GetPin(){	return pin;}/** * 子类2:synCell */ class synCell : public synObject {	string cell;public :	synCell();	void SetCell(string Cell);	string GetCell();private:};synCell::synCell(){	className = "synCell";}void synCell::SetCell(string Cell){	cell = Cell;}string synCell::GetCell(){	return cell;}/** * 系统运行主程序 */ int main(){	file://生成对象	synObject * pMyObject;	pMyObject = new synObject;	synPin * pMyPin;	pMyPin = new synPin;	pMyPin->SetPin("myPin");	synCell * pMyCell;	pMyCell = new synCell;	pMyCell->SetCell("myCell");	//插入对象	vector<synObject *> MyVector;	MyVector.empty();	MyVector.push_back(pMyObject);	MyVector.push_back(pMyPin);	MyVector.push_back(pMyCell);	//调用对象	vector<synObject *>::iterator ThisVector=MyVector.begin();	cout<<"Program begin here:"<<endl;	while( ThisVector != MyVector.end() )	{	cout << (**ThisVector).GetClass() << endl ;	if ( (**ThisVector).GetClass().compare("synCell") == 0)	{	cout << (**((synCell**)ThisVector)).GetCell() << endl ;	}	if ( (**ThisVector).GetClass().compare("synPin") == 0)	{	cout << (**(synPin**)ThisVector).GetPin() << endl ;	}	ThisVector++;	}}//程序结束