简体   繁体   English

相互返回类型的成员函数(C ++)

[英]Mutual return types of member functions (C++)

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 ? 在C ++中是否有可能有两个类,让我们称它们为AB ,这样A有一个成员函数f返回一个B类对象,而B有一个成员函数g ,它返回一个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++. 是的,我知道所有的变通方法(朋友全局函数,通过指针返回......),但我想知道上面的接口是否可以用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 . 为了举个例子,假设我试图在类A上重载operator()以返回B ,并在类B上重载以返回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. 由于我正在重载运算符,我必须按值返回(好吧,除非我想要动态分配地狱:),并且()必须作为成员函数重载,所以我不能使用全局朋友。

Yes, Implement function definitions of class A after you declared class B 是,在声明class B后实现class A函数定义

class B;

class A
{
    B f();
};

class B
{
    A g() { A a; return a; }
};

B A::f(){ B b; return b; }

Another possible way to break the dependency loop is to use a template member function, like this: 打破依赖循环的另一种可能方法是使用模板成员函数,如下所示:

struct A {
    template<typename T>  T f() { return T(); }
};

struct B {
    A g() { return A(); }
};

int main() {
    A a;
    B b = a.f<B>();
    A a1 = b.g();
    return 0;
}

It will work for operator() too, though the call syntax will be rather ugly: a.operator()<B>() 它也适用于operator(),虽然调用语法会相当丑陋: a.operator()<B>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM