代码之家  ›  专栏  ›  技术社区  ›  Jason A

为什么c++对象中的这个私有变量没有更新?复制

  •  -2
  • Jason A  · 技术社区  · 2 年前

    为了证明我的问题,我用Arduino编写了一个非常简单的程序:

    包含单个私有变量的类声明 thing

    #ifndef LED_H
    #define LED_H
    #include <Arduino.h>
    
    class LED {
      private:
        int thing;
      public:
        LED();
        void setThing(int newThing);
        int getThing();
    };
    
    #endif
    

    类实现

    #include "LED.h"
    
    LED::LED() {}
    
    void LED::setThing(int newThing) {
        thing = newThing;
    }
    
    int LED::getThing() {
        return thing;
    }
    

    我的主程序

    #include <Arduino.h>
    #include "LED.h"
    
    LED MY_LED;
    void updateLED(LED led);
    
    void setup() {
        Serial.begin(9600);
        MY_LED.setThing(1);
        Serial.println(MY_LED.getThing()); // Outputs "1" as expected
    }
    
    void loop() {
        delay(2000);
        updateLED(MY_LED);
    }
    
    void updateLED(LED led) {
        led.setThing(led.getThing() + 1);
        Serial.println(led.getThing()); // Is stuck on "2", it should be incrementing 2,3,4,5 etc
    }
    

    为什么是私人的 事情 变量未更新?我希望每次循环运行时它都会增加1。

    1 回复  |  直到 2 年前
        1
  •  2
  •   Jerry Coffin    2 年前

    这实际上与继承没有什么关系,只是参数传递。

    void updateLED(LED led) {
    

    你路过这里 led 通过 价值 ,并非参考。这意味着 带路 函数接收的是的副本 带路 调用函数时传递的对象。

    函数更新它接收的值的副本,但这对 带路 对象的副本。

    你显然想通过 带路 而是通过引用:

    void updateLED(LED &led) {
    

    这样,当它执行时 led.setThing(led.getThing() + 1); ,它将更新您传递引用的对象。

    然而,如果您要编写LED类,您还不如让它支持您实际想要的操作——也许是这样的:

    class LED {
        int thing = 0;
    public:
        LED &operator++() {
            ++thing;
            return *this;
        }
    
        void print() {
            Serial.println(thing);
        }
    };
    
    // ...
    
    LED my_led;
    for (;;) {
        ++my_led.print();
        delay(2000);
    }