开发者

calling a member function of different class from another class

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
}

The comiler reported an error. I also tried like

B obj;
obj.memberFunctionOfB(temp);

Both gave me errors that the memberFunctionOfB cannot be called. Can anyone tell me what am i开发者_如何转开发 missing

Edit

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


Your second attempt:

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

    B obj;
    obj.memberFunctionOfB(temp);
}

..., 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);
  }
};

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);
  }
};


After seeing your comment:

The compiler throws "No matching function call B::B()"

That means, there is no default constructor for class B. In your implementation, B`s constructor must be taking parameter.

So either you add a default constructor to your class, or you pass the argument to your constructor when creating an instance of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜