请求非类类型的成员

Request for member which is non-class type

本文关键字:成员 类型 请求      更新时间:2023-10-16

我有一个类MouseController。有一种方法 - 更新。

void MouseController::update(int x, int y) {
this->mX = x;
this->mY = y;
this->diffX = mX  - 650;
this->diffY = mY - 350;
calculateAngle();
}

我正在使用过剩。我想制作glutPassiveMotionFunc并放置该更新功能。

glutPassiveMotionFunc(mouse.update);

我收到以下错误:

D:\projects\cpp\glut\main.cpp|129|error: 请求成员"更新" 在"鼠标"中,其非类类型为"鼠标控制器()"

问题

通过将mouse定义为

MouseController mouse();

你定义了一个不带参数的函数,返回一个MouseController,称为mouse。然后,当您致电时

glutPassiveMotionFunc(mouse.update);

您尝试访问函数的成员update mouse。因此出现错误消息。

溶液

MouseController mouse;

(只有在MouseController::update(int,int)是静态的时才有效,但事实并非如此。

真正的解决方案

MouseController mouse;
glutPassiveMotionFunc([&](int x, int y){mouse.update(x, y)});

这是glutPassiveMotionFunc的签名

void glutPassiveMotionFunc(void (*func)(int x, int y));

如您所见,它采用一个带有两个整数作为参数的函数指针。在 C++ 中,无法获取指向非静态成员函数的指针,因为非静态成员函数具有隐式的第一个参数this该参数对于类的每个实例都是唯一的。

您可以尝试在 MouseController 中存储一个指向更新函数的函数指针,然后将其传递给 glutPassiveMotionFunc

这将为您提供一种获取指向函数的指针的方法,但仍然与需要传递给glutPassiveMotionFunc的函数指针的签名不匹配。查看其他响应者对 lambda 的解决方案来执行此操作。