引用对象成员函数的成员函数

member function referring to an object's member function

本文关键字:函数 成员 对象 引用      更新时间:2023-10-16

我是 c++ 菜鸟,所以如果这个问题结构不正确,请提前道歉。

我有一个实例化不同类对象的类,我希望主类的成员函数(请原谅我的天真语言(依次引用主类中实例化的对象的成员函数。

我附上了一个片段以供参考

福.H

class foo {
public : 
int data;
void printFunc(){
cout<< "data is"<< data;
}
};

酒吧.H

class bar {
public:
void updatebarr ();
}

酒吧.cpp

bar::bar()
{
foo foo1;
foo1.data = 1; 
// the line below is flagged as syntax error
// I want the object of type bar's updatebarr() function to be essentially be calling 
// foo::PrintFunc(). I figured this "should" work as the signatures are identical.
this->updatebarr = &foo1.printFunc(); 
}

我得到的错误是"必须调用对非静态成员函数的引用",

签名可能看起来相似,但这些不是自由函数,而是成员函数。看看这个常见问题解答!

第一个的类型是:void (foo::*)(),第二个是void (bar::*)()。看到区别了吗?

只能在其各自类型的对象上调用它们。你可以做的是:

class bar {
public:
void updatebarr(foo& f) {
f.printFunc();
}
};

指向成员方法的指针无法按照您尝试的方式工作。 您不仅有语法错误,而且还是逻辑错误,因为foo1将超出范围并在bar()退出时被销毁,从而留下updatebarr对无效的foo对象调用printFunc()

对于您正在尝试的内容,您将需要更多类似的东西:

福.H

class foo {
public : 
int data;
void printFunc(){
cout << "data is " << data;
}
};

酒吧.H

#include "foo.h"
class bar {
private:
foo foo1;
public:
bar();
void updatebarr();
};

酒吧.cpp

#include "bar.h"
bar::bar()
{
foo1.data = 1; 
}
void bar::updatebarr()
{
foo1.printFunc();
}

主.cpp

#include "bar.h"
int main()
{
bar b;
b.updatebarr();
return 0;
}

现场演示

或者,您可以将updatebarr()设置为通过 lambda 调用printFunc()std::function,例如:

福.H

class foo {
public : 
int data;
void printFunc(){
cout << "data is " << data;
}
};

酒吧.H

#include <functional>
#include "foo.h"
class bar {
private:
foo foo1;
public:
bar();
std::function<void()> updatebarr;
};

酒吧.cpp

#include "bar.h"
bar::bar()
{
foo1.data = 1; 
updatebarr = [&](){ foo1.printFunc(); };
}

主.cpp

#include "bar.h"
int main()
{
bar b;
b.updatebarr();
return 0;
}

现场演示

在这种情况下,您可以让 lambda 捕获foo对象的副本,这将为您提供非常接近原始尝试的结果,例如:

福.H

class foo {
public : 
int data;
void printFunc() const {
cout << "data is " << data;
}
};

酒吧.H

#include <functional>
class bar {
public:
bar();
std::function<void()> updatebarr;
};

酒吧.cpp

#include "bar.h"
#include "foo.h"
bar::bar()
{
foo foo1;
foo1.data = 1; 
updatebarr = [foo1](){ foo1.printFunc(); };
}

主.cpp

#include "bar.h"
int main()
{
bar b;
b.updatebarr();
return 0;
}

现场演示