gpt4 book ai didi

c++ - 调用指向成员函数的指针时出错

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:02:44 24 4
gpt4 key购买 nike

我创建了一个类,它有一个成员函数和一个结构,该结构有一个指向成员函数的函数指针作为属性。我已经用成员函数的地址初始化了结构。然后我在主函数中为该类创建了一个对象,并通过“(->*)”调用了指向成员函数的指针。但它失败了,并出现错误,指出“错误:‘右操作数’未在此范围内声明”

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

||=== Build: Debug in fptr (compiler: GNU GCC Compiler) ===| In function 'int main()':| error: 't' was not declared in this scope| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

最佳答案

指向成员函数的指针总是很难正确。但你快到了。首先,将调用更改为

(obj->*obj->t.fptr)();

然后再想想你是否真的需要使用指向嵌套在你指向的同一个类的结构中的成员的普通指针,或者某些类型别名或其他方法是否可以美化上面的怪物:)

关于c++ - 调用指向成员函数的指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56581263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com