非静态成员函数c++的无效使用
Invalid use of non-static member function c++
我正在关注这个 example。但是当我编译时,它 returns 一个错误:
Invalid use of non-static member function
行
void(Machine:: *ptrs[])() =
{
Machine::off, Machine::on
};
我试图在 class
将 static
添加到 void on();
class Machine
{
class State *current;
public:
Machine();
void setCurrent(State *s)
{
current = s;
}
static void on(); // I add static here ...
static void off(); // and here
};
但它抱怨
Invalid use of member Machine::current in static member function
你能帮我解决这个问题吗?
与静态成员函数或自由函数不同,非静态成员函数不会implicitly convert成员函数指针。
(强调我的)
An lvalue of function type T
can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.
所以你需要显式地使用&
来获取非静态成员函数的地址(即获取非静态成员函数指针)。例如
void(Machine:: *ptrs[])() =
{
&Machine::off, &Machine::on
};
如果将它们声明为静态成员函数,则应更改 ptrs
的类型(改为非成员函数指针数组)。请注意,对于静态成员函数,不显式使用 &
是可以的。例如
void(*ptrs[])() =
{
Machine::off, Machine::on
};
我正在关注这个 example。但是当我编译时,它 returns 一个错误:
Invalid use of non-static member function
行
void(Machine:: *ptrs[])() =
{
Machine::off, Machine::on
};
我试图在 class
将static
添加到 void on();
class Machine
{
class State *current;
public:
Machine();
void setCurrent(State *s)
{
current = s;
}
static void on(); // I add static here ...
static void off(); // and here
};
但它抱怨
Invalid use of member Machine::current in static member function
你能帮我解决这个问题吗?
与静态成员函数或自由函数不同,非静态成员函数不会implicitly convert成员函数指针。
(强调我的)
An lvalue of function type
T
can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.
所以你需要显式地使用&
来获取非静态成员函数的地址(即获取非静态成员函数指针)。例如
void(Machine:: *ptrs[])() =
{
&Machine::off, &Machine::on
};
如果将它们声明为静态成员函数,则应更改 ptrs
的类型(改为非成员函数指针数组)。请注意,对于静态成员函数,不显式使用 &
是可以的。例如
void(*ptrs[])() =
{
Machine::off, Machine::on
};