如何创建一个包含自身列表的结构? [英] How to create a structure which contains a list of itself?
问题描述
我想创建一个包含相同结构列表的结构,如下所示:
I want to create a structure which contains a list of same structure like this:
#include <list>
struct Url
{
CString strUrl;
std::list<Url> children;
};
int main()
{
Url u1, u2;
u1.children.push_back(u2);
}
此代码未编译.但是当我用 std::vector
替换 std::list
时,它工作正常.我怎样才能使它与 std::list
一起工作?
This code is not compiling. But when I replace std::list
with std::vector
it is working fine. How can I make this working with std::list
?
输出窗口包含以下错误.
Output window contains the following error.
c:\program files\microsoft visual studio\vc98\include\list(29) : error C2079: '_Value' uses undefined struct 'Url'
E:\test\Test.cpp(23) : see reference to class template instantiation 'std::list<struct Url,class std::allocator<struct Url> >' being compiled
c:\program files\microsoft visual studio\vc98\include\functional(185) : error C2079: 'value' uses undefined struct 'Url'
c:\program files\microsoft visual studio\vc98\include\list(285) : see reference to class template instantiation 'std::binder2nd<struct std::not_equal_to<struct Url> >' being compiled
E:\test\Test.cpp(23) : see reference to class template instantiation 'std::list<struct Url,class std::allocator<struct Url> >' being compiled
推荐答案
如果您需要解决似乎是 VC6 错误的方法,请动态创建列表:
If you need a workround for what seems to be a VC6 bug, create the list dynamically:
#include <list>
#include <string> // I don't use MFC
struct Url
{
std::string strUrl;
std::list<Url> * children;
Url() {
children = new std::list <Url>;
}
~Url() {
delete children;
}
};
int main()
{
Url u1, u2;
u1.children->push_back(u2);
}
有些人问为什么在
Url array[5];
例如作为会员就不会.我在标准中也找不到任何东西,但是 sizeof( std:;list <T>)
不依赖于它是一个列表的东西.假设列表被实现为(这里有一些伪 C++):
for example as a member would not be. I can't find anything in the standard either, but sizeof( std:;list <T>)
is not dependent on the thing it is a list of. Suppose list was implemented as (some pseudo C++ here):
list <T> {
listEntry <T> * first;
};
那么就没有未知的尺寸需要处理了.考虑以下解决提问者问题的最小代码:
then there is no unknown size to deal with. Consider the following minimal code that addresses the questioners problem:
template <typename T> struct A {
};
struct B {
A <B> b;
};
我看不出有任何不合法的理由.
I can't see any possible reason that this should not be legal.
这篇关于如何创建一个包含自身列表的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!