我有一个Visual Studio 2013 C ++ 11项目,我已经定义了一个树状结构(迭代器的每个元素本身就是一个容器)。
struct some_tree;
class some_tree_iterator
: public boost::iterator_facade<
some_tree_iterator,
some_tree,
std::forward_iterator_tag,
some_tree>
{
public:
// ...
private:
// error C2027: use of undefined type 'some_tree'
some_tree dereference() const { return some_tree( /*init values*/ ); };
// ...
};
struct some_tree
{
some_tree_iterator begin();
some_tree_iterator end();
std::string value() const;
};
int main(int argc, char* argv[])
{
some_tree foo;
for (auto x : foo)
{
std::cout << x.name() << std::endl;
for (auto y : x)
{
std::cout << "\t" << y.value() << std::endl;
}
}
return 0;
}
解决此use of undefined type
问题的唯一方法是返回指向新some_tree
容器的指针吗?像这样:
std::shared_ptr<some_tree> some_tree_iterator::dereference() const
{
return std::make_shared<some_tree>( /* init values*/ );
};
答案 0 :(得分:1)
两种方法:
在定义之前,不得引用该类。所以你必须这样做:
struct some_tree;
class some_tree_iterator
{
public:
// ...
private:
some_tree dereference() const;
// ...
};
struct some_tree
{
some_tree_iterator begin();
some_tree_iterator end();
std::string value() const;
};
some_tree some_tree_iterator::dereference() const { return some_tree( /*init values*/ ); };
此外,您可能喜欢STL并在struct some_tree
内定义迭代器(实际上,STL&#39;迭代器是模板,所以它们在类中定义,即使在其他地方声明):
struct some_tree
{
class iterator
: public boost::iterator_facade<
iterator,
some_tree,
std::forward_iterator_tag,
some_tree>
{
public:
private:
some_tree dereference() const { return some_tree( /*init values*/ ); };
};
iterator begin();
iterator end();
std::string value() const;
};
答案 1 :(得分:0)
如果您需要多个使用彼此作为完整类型的类,您可以使用以下内容:
class TestClass1;
class TestClass2;
class TestClass1
{
int val;
TestClass2 foo();
};
class TestClass2
{
int val;
TestClass1 foo();
};
TestClass2 TestClass1::foo()
{
/* ... */
}
TestClass1 TestClass2::foo()
{
/* ... */
}