本文介绍了我怎样才能将此stl列表传递给fun函数并访问该函数中的struct?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的基类
i have an base class like this
class Base
{
public:
virtual void fun() const =0;
};
这样的派生类:
Derived class like this :
class Derived:public Base
{
virtual void fun()
{
//implemtation of fun
}
};
我有一个全局结构
I had an global structure
struct Mystruct
{
int a;
char *b;
}MYSTRUCT;
我在列表stl中将结构添加为
I added the structure in list stl as
std::list< MYSTRUCT* > SS1;
List = new MYSTRUCT;
vector<MYSTRUCT*>SS;
SS.push_back( List);
现在我可以将此stl列表传递给fun函数并访问该函数中的结构吗?
Now can i pass the this stl list to the fun function and access the struct in the function?
推荐答案
struct MS {
bool bDataOwner;
int iData;
char* pData;
MS() : bDataOwner(false), iData(0), pData(NULL) {}
~MS() { if (bDataOwner && pData) delete pData /*use free(pData) for C allocations*/; }
};
typedef std::list<ms*> lstPMS;
typedef lstPMS::iterator iterPMS;
class lstOwnerMS : private lstPMS
{
public:
virtual ~lstOwnerMS() { Empty(); }
void AddData(const MS* pMS) {
lstPMS::push_back(pMS);
}
iterPMS GetHeadPosition() const {
return lstPMS::begin() < lstPMS::end() ? lstPMS::begin() : NULL;
}
MS* GetNext(iterPMS& iter) const {
MS* pResult(NULL);
if (iter < lstPMS::end()) {
pResult = iterPMS;
iterPMS++;
} else {
iterPMS = NULL;
}
return pResult;
}
void Empty() {
while (!lstPMS::empty()) {
delete lstPMS::front();
lstPMS::pop_front();
}
}
};
class IBase
{
public:
virtual void ProcessPMSList(lstOwnerMS& lst) const = 0;
};
class Test : public IBase
{
public:
virtual void ProcessPMSList(lstOwnerMS& lst) const
{
// elements navigation
iterPMS iter(lst.GetHeadPosition());
while (iter) {
MS* pMs(lst.GetNext(iter));
if (pMs) {
cout << pMS->iData << " ";
}
}
}
};
int main()
{
lstOwnerMS lstOwner;
lstOwner.AddData(new MS);
MS* pMS(new MS);
pMS->bDataOwner = true;
pMS->pData = new char[2];
strcpy_s(pMS->pData, 2, ".");
lstOwner.AddData(pMS);
Test test;
test.ProcessPMSList(lstOwner);
return 0;
};
这篇关于我怎样才能将此stl列表传递给fun函数并访问该函数中的struct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!