无效使用非静态成员函数C ++ [英] Invalid use of non-static member function c++

查看:311
本文介绍了无效使用非静态成员函数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循以下示例。但是当我编译时,它返回一个错误:

I am following this example. But when I compile, it returns an error:


非静态成员函数的无效使用

Invalid use of non-static member function

在线

void(Machine:: *ptrs[])() = 
  {
    Machine::off, Machine::on
  };

我尝试将静态添加到 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
};

但它抱怨


无效使用成员Machine :: current的静态成员函数

Invalid use of member Machine::current in static member function

您能帮我解决这个问题吗?

Can you help me fix this?

推荐答案

与静态成员函数或自由函数不同,非静态成员函数不会隐式转换到成员函数指针。

Unlike static member functions or free functions, non-static member functions won't implicitly convert to member function pointers.

(强调我的意思)


函数类型 T 的左值可以隐式转换为指向该值的prvalue指针功能。 这不适用于非静态成员函数,因为引用非静态成员函数的左值不存在。

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.

因此,您需要显式使用& 来获取非静态成员函数的地址(即,获取非静态成员函数的指针)。例如

So you need to use & explicitly to take the address of the non-static member functions (i.e. to get non-static member function pointers). e.g.

void(Machine:: *ptrs[])() = 
  {
    &Machine::off, &Machine::on
  };

如果将它们声明为静态成员函数,则应更改的类型ptrs (指向非成员函数指针的数组)。请注意,对于静态成员函数,最好不要显式使用& 。例如

If you declare them as static member function, you should change the type of ptrs (to array of non-member function pointers). Note that for static member function it's fine to not use & explicitly. e.g.

void(*ptrs[])() = 
  {
    Machine::off, Machine::on
  };

这篇关于无效使用非静态成员函数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆