【问题标题】:Error: Cannot take the address of an rvalue of type 'void'错误:无法获取“void”类型的右值的地址
【发布时间】:2020-05-14 10:47:12
【问题描述】:

当我在 MBED 中使用 InterruptIn 类时,我开始收到此错误。
这是我试图调用的 fall 函数的定义:

这是我的代码:

   void Sensor::contador(int cont){
          cont++;
   }  
   int Sensor::medidaSensor(){
    //Se activa el watchdog:
       Timer timer;
       timer.start();
       int npulsos=0;
       while(1){
           //Cuenta los pulsos durante 5ms
           if (timer.read_ms() < 5)
           {
              vcomp.fall(&contador(npulsos)); // <= compilation error here
           }
           else{
               //Kick the watchdog to reset its timer
                watchdogTimer.kick();
           }
       }
       return npulsos;
   }

【问题讨论】:

  • contador() 返回void,因此&amp;contador(npulsos) 返回一个void 类型的右值,您正在尝试获取地址。你想将什么传递给fall 函数?
  • void 表示没有价值,不是object without value。还请将fall 的定义发布为文本,而不是图像(阅读idownvotedbecau.se/imageofcode)。

标签: c++ function-pointers rvalue mbed


【解决方案1】:

来自您的 fall 定义

  • obj - 指向要调用其成员函数的对象的指针
  • 方法 - 指向要调用的成员函数的指针

我想你想要:

vcomp.fall(this, &Sensor::contador);

即在当前对象上调用 contador 方法。

但是请注意,这不接受回调成员函数的参数,因此您不能调用当前的 contador 方法:您必须将计数设置为类中的字段,或者例如使用不同的 fall() 签名,例如接受回调函数的签名。 (恐怕我的 C++ lamda 生锈了,所以我不确定你是否可以像在其他语言中那样使用带有闭包的 lambda 来复制它,或者这是否会导致 lambda 的生命周期出现问题。)

在任何情况下,在latest version of the documentation 中,这个版本的fall 方法被标记为弃用,取而代之的是回调版本。

【讨论】:

    【解决方案2】:

    这是调用fall函数的正确方法(根据您附上的图片)我们不知道这个函数做什么但没关系:

      void Sensor::contador(int* cont){
              ++(*cont);
       }  
       int Sensor::medidaSensor(){
        //Se activa el watchdog:
           Timer timer;
           timer.start();
           int npulsos=0;
           while(1){
               //Cuenta los pulsos durante 5ms
               if (timer.read_ms() < 5)
               {
                  vcomp.fall(this,Sensor::contador);
               }
               else{
                   //Kick the watchdog to reset its timer
                    watchdogTimer.kick();
               }
           }
           return npulsos;
       }
    

    【讨论】:

    • 它可能不是&amp;npulsos,因为它是一个 int 并且没有成员函数。它应该是Sensor 的地址(即this
    • 也许吧!这种模棱两可和混乱。也许 T* 对象(来自 fall 函数)它是 M 方法的参数(上下文)来操作。所以我认为我的回答没有错。无论如何,你会同意我的观点,这个问题是模棱两可的
    • 这不是模棱两可的;您不能在 int 上调用成员函数
    • @AsteroidsWithWings- 我匆匆忙忙,错过了附图中的小字:“obj - 指向要调用成员函数的对象的指针” - 所以绝对是对象(this)本身。我的错误我会修正我的答案。谢谢。 (请再次推动投票)
    • 没错。这是一种常见的 C 风格回调模式。
    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多