成员函数的相互返回类型 (C++)
C++ 中是否可以有两个类,我们称它们为 A
和 B
,这样 A
有一个成员函数 f< /code> 返回类
B
的对象,并且 B
有一个成员函数 g
返回类 A< 的对象/代码>?
(下面的文字只是为了表明我已经“完成了我的作业”。)
问题在于,当第一个定义的类中的函数具有不完整的返回类型时,如何编写这些函数的签名。前向声明在这里没有帮助,因为对象是按值返回的。
是的,我知道所有的解决方法(朋友全局函数,通过指针返回,...),但我只想知道上面的接口是否可以在 C++ 中实现。举个例子,假设我试图在类 A
上重载operator()以返回B
,并在类B
上重载operator()返回A
。由于我是重载运算符,所以我必须按值返回(好吧,除非我想要动态分配地狱:),并且 () 必须作为成员函数重载,所以我不能使用全局友元。
Is it possible in C++ to have two classes, let's call them A
and B
, such that A
has a member function f
that returns an object of class B
, and B
has a member function g
that returns an object of class A
?
(The text below is just to show I have "done my homework".)
The problem is just how to write signatures of these functions, when the one in first defined class will have an incomplete return type. Forward declarations don't help here, because objects are returned by value.
Yes, I know all the workarounds (friend global functions, returning by pointer,...), but I would just like to know if the interface as above can be implemented in C++. For the sake of an example, let's say that I am trying to overload operator() on class A
to return B
, and on class B
to return A
. Since I am overloading operators, I must return by value (well, unless I want a dynamic allocation hell:), and () must be overloaded as a member function, so I can't use global friends.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,在声明
class B
之后实现class A
的函数定义Yes, Implement function definitions of
class A
after you declaredclass B
打破依赖循环的另一种可能方法是使用模板成员函数,如下所示:
它也适用于operator(),尽管调用语法会相当难看:
a.operator()( )
Another possible way to break the dependency loop is to use a template member function, like this:
It will work for operator() too, though the call syntax will be rather ugly:
a.operator()<B>()