【发布时间】:2019-06-13 13:08:50
【问题描述】:
我创建了一个具有成员函数的类和一个结构,该结构具有指向成员函数的函数指针作为属性。我已经用成员函数的地址初始化了结构。然后我在主函数中为该类创建了一个对象,并通过“(-> *)”调用了指向成员函数的指针。但是它失败了,错误提示“错误:'正确的操作数'没有在这个范围内声明”
//Header
#ifndef A_H
#define A_H
class A
{
public:
typedef struct
{
void (A::*fptr) ();
}test;
test t;
public:
A();
virtual ~A();
void display();
protected:
private:
};
#endif // A_H
//A.cpp
#include "A.h"
#include <iostream>
using namespace std;
A::A()
{
t.fptr = &A::display;
}
A::~A()
{
//dtor
}
void A::display()
{
cout << "A::Display function invoked" << endl;
}
//Main
#include <iostream>
#include "A.h"
using namespace std;
int main()
{
cout << "Pointer to Member Function!" << endl;
A *obj = new A;
(obj->*t.fptr)();
return 0;
}
||=== 构建:在 fptr 中调试(编译器:GNU GCC 编译器)===|在 函数'int main()':|错误:未在此范围内声明“t”| ||=== 构建失败:1 个错误,0 个警告(0 分钟,1 秒)===|
【问题讨论】:
-
制作更简单的示例以使用新语法。并在指向函数成员的指针之前尝试指向数据成员的指针。
-
函数指针声明是一团糟,除非您使用
using void_func = void (A::*) (void);中的别名 我不得不承认,我不太了解您对test结构的使用
标签: c++ member-function-pointers