简体   繁体   中英

“Pass” function call from class to class, C++

Is there a way to pass a function call from class to class? For example:

//foo.cpp
foo::foo
{
  ...
  myfoo2 = new foo2();
  ...
}

//foo2.h
class foo2
{
  ...
  public:
  void method1();
  void method2(int arg2)
  ...
}

Now I want to use the method of foo2 (eg method2) from outside of the foo class without having to implement the following:

//foo.cpp
...
void foo::method2(int arg2)
{
  myfoo2->method2(arg2);
}

The problem is, that i have quite a lot of these, and this would take a lot of space and does not look nice. Is there any other solution, or at lest a short version with the same effect?

Thank you in advance!

You can use private inheritance to include a foo2 object in your foo class, without creating an is-a relationship. Then you can simply expose the function with a using statement, like so:

class foo : private foo2
{
public:
    using foo2::method2;
};

If foo is just a handle or wrapper for a foo2 it might make sense to overload operator-> :

#include <iostream>

class foo2 {
public:
  void method1(){ std::cout << "method1\n"; }
  void method2(int /*arg2*/) { std::cout << "method2\n"; }
};

class foo {
  foo2 myfoo2;
public:
  foo2* operator->() { return &myfoo2; }
};

int main() {
  foo f;
  f->method1();
  f->method2(1);
}

Live demo .

Why not have one method in your foo class that returns a pointer (or const pointer) to your foo2 class like so:

class foo
{
public:
    foo2* getFoo2() const { return foo2_; }

private:
    foo2* foo2_;
};

Then on the outside you can use it like so:

foo f;
auto f2 = f.getFoo2();
f2->method1();
f2->method2(/*args*/);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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