首页 > 解决方案 > 填充指向返回结构的类获取函数的指针数组

问题描述

我正在尝试填充指针数组。我需要 MyClass 的两个(或更多)实例的 myVar 数据。但由于某种原因,我没有得到我想要的结果。

头文件:

typedef struct {
    int value;
    int otherValue; // We do nothing with otherValue in this example.
} mytype_t;

class MyClass {
    public:
        MyClass(void) {}
        ~MyClass(void) {}
        void set(float _value) {
            myVar.value = _value;
        }
        mytype_t get(void) { // We get the data through this function.
            return myVar;
        }
    protected:
    private:
        mytype_t myVar; // Data is stored here.
};

cp文件:

MyClass myInstances[2];

int main(void) {

    // Set private member data:
    myInstances[0].set(75); 
    myInstances[1].set(86);

    mytype_t *ptr[2];

    ptr[0] = &(myInstances[0].get());
    ptr[1] = &(myInstances[1].get());

    Serial.print(ptr[0]->value); // Prints 75 -> As expected!
    Serial.print(":");
    Serial.print(ptr[1]->value); // Prints 86
    Serial.print("\t");

    for (int i = 0; i < 2; i++) {
        Serial.print(myInstances[i].get().value); // Prints 75, and next iteration 86 -> As expected.
        if (i == 0) Serial.print(":");
        ptr[i] = &(myInstances[i].get()); // Set ptr
    }
    Serial.print("\t");

    Serial.print(ptr[0]->value); // Prints 86 -> Why not 75..?
    Serial.print(":");
    Serial.print(ptr[1]->value); // Prints 86
    Serial.println();
}

程序输出:

75:86   75:86   86:86

并不是:

75:86   75:86   75:86

为什么它指向另一个实例(值为 86)呢?我该如何解决?还是我想要的东西不可能?

PS 代码在PC平台上运行。我正在使用我自己的基于 Arduino 语法的 Serial 类。

标签: c++pointersstruct

解决方案


您正在分配指向从返回的临时对象的指针get。您没有分配指向MyClass对象内部的指针。更改您的代码,以便get返回引用而不是副本。

mytype_t& get(void) { // We get the data through this function.
        return myVar;
}

那应该使您的程序正常工作。但是,返回对另一个对象内部的引用并不是一种好的做法。您可能应该重新考虑您的设计。


推荐阅读