简体   繁体   English

填充指向返回结构的类get函数的指针数组

[英]Fill array of pointers to class get function that returns struct

I'm trying to fill an array of pointers. 我正在尝试填充一个指针数组。 I need the myVar data of the two (or more) instances of the MyClass. 我需要MyClass的两个(或更多)实例的myVar数据。 But for some reason I am not getting the results I want. 但是由于某种原因,我没有得到想要的结果。

Header file: 头文件:

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.
};

Cpp file: Cpp文件:

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();
}

The program outputs: 程序输出:

75:86   75:86   86:86

And not: 并不是:

75:86   75:86   75:86

Why is it pointing to the other instance (with value 86) instead? 为什么它指向另一个实例(值86)呢? And how can I fix it? 我该如何解决? Or is the thing I want not possible? 还是我想要的东西不可能?

PS The code is run on a PC platform. PS该代码在PC平台上运行。 I am using my own Serial class based on the syntax of Arduino. 我正在使用基于Arduino语法的自己的Serial类。

You are assigning pointers to the temporary objects returned from get . 您正在将指针分配给从get返回的临时对象。 You are not assigning pointers to the internals of your MyClass objects. 您没有将指针分配给MyClass对象的内部。 Change your code so that get returns a reference instead of a copy. 更改您的代码,以便get返回引用而不是副本。

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

That should make your program work. 那应该使您的程序正常工作。 However it's not considered good practise to return a reference to the internals of another object. 但是,返回对另一个对象内部的引用不是一种好习惯。 You should probably reconsider your design. 您可能应该重新考虑您的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM