调用不同类的成员函数与另一个类 [英] calling a member function of different class from another class

查看:238
本文介绍了调用不同类的成员函数与另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类A和B.控制是在类A的成员函数之一。成员函数计算结果,我现在想要发送此值到类B的成员函数之一,我试过下面的方式,但它dint工作

I have two classes A and B. The control is inside one of the member functions of class A. The member function calculates a result and i now want to send this value to one of the member functions of class B, I tried the following way, yet it dint work


int memberFunctionOfA()
{
... //results are stored in some temporary value, say temp

B::memberFunctionOfB(temp);  // the way i tried
}

comiler报告错误。我也试过像

The comiler reported an error. I also tried like


B obj;
obj.memberFunctionOfB(temp);

两个都给我的错误,memberFunctionOfB不能被调用。谁能告诉我我失踪了什么

Both gave me errors that the memberFunctionOfB cannot be called. Can anyone tell me what am i missing

编辑

继承自A.他们都是独立的。

Class B is not inherited from A. They both are independent. Both the member functions are public and non static

推荐答案

您的第二次尝试:

int memberFunctionOfA()
{
... //results are stored in some temporary value, say temp

    B obj;
    obj.memberFunctionOfB(temp);
}

...看起来完全有效。我们需要B的定义来进一步帮助。 B的定义应该最小化,假设B中的成员函数是非静态的:

..., looks perfectly valid. We will need the definition of B to help further. B's definition should minimally have, assuming that the member function in B is non-static:

class B
{
public:
  void memberFunctionOfB(const TypeOfTemp &temp);
};

// Later in class A's definition
class A
{
public:
  int memberFunctionOfA()
  {
    ... //results are stored in some temporary value, say temp

    B b;
    b.memberFunctionOfB(temp);
  }
};

如果B中的成员函数是静态的,那么这应该工作:

If the member function in B is static, then this should work:

class B
{
public:
  static void memberFunctionOfB(const TypeOfTemp &temp);
};

...

class A
{
public:
  int memberFunctionOfA()
  {
    ... //results are stored in some temporary value, say temp

    B::memberFunctionOfB(temp);
  }
};

这篇关于调用不同类的成员函数与另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆