打破 C++ 中的循环依赖
我正在尝试解决以下循环依赖问题:
typedef std::map<int, my_class> my_map;
class my_class {
...
private:
my_map::iterator iter;
};
class otherclass{
public:
my_map::iterator getIter();
private:
my_map map;
};
编译器不喜欢这样,因为 my_class 没有在 typedef 之前声明。
如果我尝试像这样前向声明 myclass:
class my_class;
typedef std::map<int, my_class> my_map;
class my_class {
...
private:
my_map::iterator iter;
};
class otherclass{
public:
my_map::iterator getIter();
private:
my_map map;
};
我收到“错误:'my_class' 的前向声明”。
我怎样才能打破这个恶性循环呢?
很抱歉,但我必须修改我的问题,因为我注意到我的表述略有错误。
以下是我的问题的正确表述:
class my_container;
typedef std::map<int, my_container> my_map;
class my_class {
...
private:
my_map::iterator iter;
};
class my_container {
public:
my_class a_method();
private:
vector<my_class> v;
};
class otherclass{
public:
my_map::iterator a_method();
my_class another_method();
my_container yet_another_method();
private:
my_map map;
};
对此感到抱歉
I have the following cyclic dependency problem I am trying to solve:
typedef std::map<int, my_class> my_map;
class my_class {
...
private:
my_map::iterator iter;
};
class otherclass{
public:
my_map::iterator getIter();
private:
my_map map;
};
The compiler does not like this, since my_class was not declared before the typedef.
if I try to forward-declare myclass like this:
class my_class;
typedef std::map<int, my_class> my_map;
class my_class {
...
private:
my_map::iterator iter;
};
class otherclass{
public:
my_map::iterator getIter();
private:
my_map map;
};
I get an "error: forward declaration of 'my_class'".
How can I break this vicious cycle?
I'm sorry but I have to revise my question, as I have noticed that my representation is slightly wrong.
The following is the correct representation of my problem:
class my_container;
typedef std::map<int, my_container> my_map;
class my_class {
...
private:
my_map::iterator iter;
};
class my_container {
public:
my_class a_method();
private:
vector<my_class> v;
};
class otherclass{
public:
my_map::iterator a_method();
my_class another_method();
my_container yet_another_method();
private:
my_map map;
};
Sorry about this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
循环依赖通常是一件坏事。你能重新考虑一下你的设计吗?
my_class
真的需要知道它的容器是什么吗?如果这不切实际,您可以只使用
my_container*
来代替my_map
的迭代器吗?编译器不会因为使用不完整类型的指针而出现问题。Circular dependencies are generally a Bad Thing. Can you re-think your design a bit? Does a
my_class
really need to know what its container is?If that's not practical, instead of an iterator into
my_map
, could you get away with just amy_container*
? The compiler won't have a problem with using an incomplete type for the pointer.将 my_map 作为 my_class 的成员,如下所示:
如果您不想始终使用
my_class::
,则创建另一个 typedef。put my_map as a member in my_class, like this:
If you don't want to always use
my_class::
, then make another typedef.您可以将 typedef 放入 my_class 中:
You could put the typedef inside my_class:
怎么样:
How about: