2008年(909)
分类:
2008-05-06 21:37:30
赵湘宁
class synObject { public : synObject(); string GetClass(); string className; }; synObject::synObject() { className = "synObject"; } string synObject::GetClass() { return className; } 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; } 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; }现在将这些类压入向量列表。
synObject * pMyObject; pMyObject = new synObject; synPin * pMyPin; pMyPin = new synPin; (*pMyPin).SetPin("myPin"); synCell * pMyCell; pMyCell = new synCell; (*pMyCell).SetCell("myCell"); vector当遍历向量时,我只能访问公共的(基类)方法:不能访问派生的方法。MyVector; vector ::iterator ThisVector; MyVector.empty(); MyVector.push_back(pMyObject); MyVector.push_back(pMyPin); MyVector.push_back(pMyCell);
for ( ThisVector = MyVector.begin(); ThisVector != MyVector.end(); ThisVector ) { cout << (**ThisVector).GetClass() << endl ; if ( (**ThisVector).GetClass().compare("synClass") == 0) { cout << (**ThisVector).GetCell() << endl ; } if ( (**ThisVector).GetClass().compare("synPin") == 0) { cout << (**ThisVector).GetPin() << endl ; } }
pMyCell->SetCell("myCell");代替
(*pMyCell).SetCell("myCell");更重要的是,不要使用迭代器访问向量元素,而要使用重载的“[]”操作符
vector < synObject * >::iterator ThisVector= MyVector.begin(); for (int i =0; ThisVector!=MyVector.end(); i) { cout << MyVector[i]->GetClass(); }另外,我对你的代码有一些风格上的建议,这很重要: