1

我正在尝试在 C++ 中设置非静态函数的引用。我引用的函数不是来自同一个 c++ 文件,我得到错误提示:

无法创建指向成员函数的非常量指针。

主文件

#include <iostream>
#include "Test.hpp"

class testClass {
public:
    void (*update) (void);
};

int main() {
    testClass tc;
    test t;
    tc.update = &t.update; //This is where the error occurs
    return 0;
}

测试.hpp

#ifndef Test_hpp
#define Test_hpp

#include <stdio.h>

class test {
public:
    void update() {
        //Do something
    }
};

#endif /* Test_hpp */

我的问题是如何在不将测试类中的更新设置为静态的情况下做到这一点?

static void update() {
    //Do something
}

使用此代码它可以工作,但就像我说过的那样,我不希望这个函数是静态的。

编辑: 因为我很愚蠢,所以我没有提到班级测试应该能够有所不同。同样对于我已经得到的答案,我了解到 tc.update = &t.update; 是错的。

例如 :

#include <iostream>
#include "Test.hpp"
#include "anotherTestClass.hpp"

//I do not want to use templates if possible
class testClass {
public:
    void (*update)(void);
};

int main() {
    testClass tc;
    test t;
    tc.update = &test.update; //I know this is wrong now.
    testClass tc2;
    anotherTestClass atc;
    tc2.update = &atc.update;
    //p.s. I'm bad with c++
}

我现在得到的错误是。

Assigned to 'void (*)()' from incompatible type 'void (test::*)()'

另一件事是我正在使用 XCode 进行编程,我相信它使用 LLVM-GCC 4.2 作为编译器。

4

2 回答 2

2
class test {
public:
    void update() {
        //Do something
    }
};

class testClass {
public:
    void (test::* update) (void);
};

int main() {
    testClass tc;
    test t;
    tc.update = &test::update; 
    return 0;
}
于 2017-08-05T22:18:00.070 回答
1

你的方法本质上是错误的。

成员函数指针。

中的成员testClass

void (*update) (void);

是一个函数指针,与方法函数指针不同。这就是为什么为了编译你应该切换到一个static方法(本质上是一个“正常”函数)。

方法函数指针应包含有关该方法所属类的静态信息。

实际上正确的方法是:

void (test::* ptr_method)(void);  // a member pointer to test class

这样命名的变量ptr_method就是类test指针的方法。

然后,

获取方法的地址。

您的声明:

tc.update = &t.update; //This is where the error occurs

完全是错误的。类方法的地址与该类的对象无关。

您可以使用以下语法获取方法的地址:

&CLASS_NAME::METHOD_NAME;

实际上,该声明应该类似于:

tc.update = &test::update;

额外的建议。

通过方法指针调用方法。

一旦有了方法指针,就不会立即调用与其关联的方法。正如我之前所说,方法的地址与该类的对象无关,因此如果要调用该方法,则需要向编译器提供有关必须调用该方法的对象的信息。

语法类似于:

(OBJECT.*METHOD_POINTER)(ARGS...);

在这里,我提出了一个简单的演示,它显示了我刚才所说的所有内容。

于 2017-08-05T22:27:01.557 回答