C++ 从另一个类调用不同类的成员函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4986574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calling a member function of different class from another class
提问by CHID
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
我有两个类 A 和 B。控件在类 A 的成员函数之一内。成员函数计算结果,我现在想将此值发送到类 B 的成员函数之一,我尝试了以下方法,但它确实有效
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
两者都给了我无法调用 memberFunctionOfB 的错误。谁能告诉我我错过了什么
Edit
编辑
Class B is not inherited from A. They both are independent. Both the member functions are public and non static
B 类不是从 A 继承的。它们都是独立的。成员函数都是公共的和非静态的
回答by Michael Goldshteyn
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:
...,看起来完全有效。我们将需要 B 的定义来进一步帮助。B 的定义应该至少有,假设 B 中的成员函数是非静态的:
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:
如果 B 中的成员函数是静态的,那么这应该有效:
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);
}
};
回答by Nawaz
After seeing your comment:
看到你的评论后:
The compiler throws "No matching function call B::B()"
编译器抛出“没有匹配的函数调用 B::B()”
That means, there is no default constructor for class B
. In your implementation, B`s constructor must be taking parameter.
这意味着, class 没有默认构造函数B
。在您的实现中,B 的构造函数必须带参数。
So either you add a default constructor to your class, or you pass the argument to your constructor when creating an instance of it.
因此,要么向类添加默认构造函数,要么在创建它的实例时将参数传递给构造函数。