在 C++ 中使用指针时,对象 属性 未按预期更改

Object property not changing as expected when using pointers in C++

我正在尝试使用 C++ 中的 classes。来自 Java 世界,它们略有不同。

我想做的事情应该很明显:我有一个名为 SomeClass 的 class,它包含一个 int。然后我有一个名为 A 的 class,其中

// Create a class holding just an integer.
class SomeClass {
    public:

        int _value;

        SomeClass(int value) {
            this->_value = value;
        }
};

class A {

    private:
        // The property _someClassPointer holds a pointer to a SomeClass object.
        SomeClass *_someClassPointer;
    public:

        // We can set a SomeClass instance as a property of the A class.
        void setSomeClass(SomeClass *someClassPointer) {
            // It copies the local pointer value to the property.
            this->_someClassPointer = someClassPointer;
        }

        // We can retrieve the integer that the SomeClass instance holds.
        // We're assuming _someClassPointer does not point to NULL.
        int getValueOfSomeClass() {
            this->_someClassPointer->_value;
        }
};

void setup() {
    Serial.begin(9600);
}

void loop() {

    // Instantiate SomeClass object with int(5) argument
    SomeClass someClass(5);

    Serial.println(someClass._value); // It prints 5, as expected

    // Instantiate an A object by its default constructor
    A a;

    // Pass the address of someClass to the method
    a.setSomeClass(&someClass);

    // Set the value of someClass to 6
    someClass._value = 6;

    Serial.println(a.getValueOfSomeClass()); // It prints 0
}

为什么打印的是 0 而不是 6

您的函数没有返回值。

int getValueOfSomeClass() {
    return this->_someClassPointer->_value;
}

编辑: 我应该提到你可以删除 'this->' 因为它隐含在非静态方法中。

int getValueOfSomeClass() {
    return _someClassPointer->_value;
}

第二个问题:这是按值传递参数、按引用传递参数和按指针传递参数的区别。这有点棘手,但您可以在网上找到很多关于这个主题的信息。