reference to non-static member
时间: 2023-04-28 12:01:26 浏览: 182
"reference to non-static member" 指的是在静态上下文中引用非静态成员变量或函数。在静态上下文中,只能访问静态成员,不能访问非静态成员。因此,如果在静态函数中调用非静态函数或访问非静态变量,就会引发这种错误。
相关问题
QT reference to non-static member function must be
This error message usually occurs when you try to pass a non-static member function as a callback function to a Qt signal.
To solve this issue, you need to ensure that the member function is declared as `static` or that it is a non-member function. If you cannot declare the member function as static, you can use a lambda function or a `std::bind` expression to wrap the member function into a callable object that can be passed as a callback.
For example, suppose you have a class `MyClass` with a non-static member function `myFunction`, and you want to connect a signal to this function:
```cpp
class MyClass : public QObject
{
Q_OBJECT
public:
void myFunction(int value);
};
MyClass myObject;
connect(mySignal, &MySignal::valueChanged, &myObject, &MyClass::myFunction); // Error!
```
Since `myFunction` is not static, you will get the error message "reference to non-static member function must be called" when you try to compile this code. To solve this, you can wrap `myFunction` into a lambda function:
```cpp
class MyClass : public QObject
{
Q_OBJECT
public:
void myFunction(int value);
};
MyClass myObject;
connect(mySignal, &MySignal::valueChanged, &myObject,
[](int value){ myObject.myFunction(value); }); // OK!
```
Alternatively, you can use `std::bind`:
```cpp
class MyClass : public QObject
{
Q_OBJECT
public:
void myFunction(int value);
};
MyClass myObject;
connect(mySignal, &MySignal::valueChanged, &myObject,
std::bind(&MyClass::myFunction, &myObject, std::placeholders::_1)); // OK!
```
Both of these solutions create a callable object that calls `myFunction` on `myObject` with the correct parameter.
reference to non-static member function must be called
这个错误通常出现在尝试调用非静态成员函数时,因为非静态成员函数需要通过对象来调用。如果你尝试直接调用非静态成员函数,就会出现“reference to non-static member function must be called”的错误。解决这个问题的方法是要么将该函数定义为静态成员函数,要么通过对象来调用该函数。
以下是一个例子,演示了如何通过对象来调用非静态成员函数:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
class MyClass {
public:
void printVector(std::vector<int>& vec) {
std::for_each(vec.begin(), vec.end(), printInt);
}
private:
static void printInt(int i) {
std::cout << i << " ";
}
};
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
MyClass obj;
obj.printVector(vec); // 通过对象来调用非静态成员函数
return 0;
}
```