4

I have a class, suppose a.cpp. In the private property of this class, I have a pointer to b.cpp and c.cpp where b.cpp is the implementation of a virtual interface class, lets call d.cpp. Also, in the private property of c.cpp, I have a pointer to the interface class, d.cpp.

I want to access one of the methods of class a.cpp in b.cpp class. How can I do that?

The example can be ok, let me give some methods in the classes

class A{
private:
  B *_classB;
  C *_classC;
public:
  int add(int, int);
}

Now, the interface class is D So, in class D, we have

class D{
public:
  virtual int mul(int, int) = 0;
}

Now, the class B is the implementation of interface class D So, B looks like:

class B{
private:
   int first_num;
   int second_num;

public:
   virtual int mul(int a, int b);
}

and class C also has pointer to the interface class, so C looks like

class C{
private:
  D *_classD;
}

Now, I want to call the method int add(int, int) in class B.

4

3 回答 3

1

由于 A 包含 B 并且没有其他关系,因此您需要在 B 类中保留指向所有者 A 的指针

于 2013-08-12T14:56:16.987 回答
1

你需要一个类的实例A,或者你需要创建add一个静态成员函数A

换句话说,static解决方案是这样的:

class A
{
 ...
 static int add(int, int);
};

然后一个电话会看起来:

...
A::add(x, y);
...

或者:

class B{
private:
   int first_num;
   int second_num;

public:
   virtual int mul(int a, int b);
   int add(const A& a, int x, int y)
   {
        return a.add(x, y);
   }
}

从 A 中的函数来看,它看起来像这样:

void A::func(int x, int y)
{
     b->add(*this, x, y);
}

还有其他几种解决方案。但是如果没有更多关于你的实际用例的信息,这可能会尽可能好。

于 2013-08-12T14:57:58.977 回答
0

您可以将 A 类型的对象作为 B 的数据成员,也可以将 A 的指针作为 B 的数据成员。因为在您创建的类中,A 和 B 之间没有关系。除非您想做继承,我认为这不是这里的问题。

于 2013-08-12T15:01:09.227 回答