C++/Arduino Array in class

Asked

Viewed 265 times

3

I have a problem using an array of pointers, I need to create an array with pointers referencing to an integer value of each object of another class.

Example:

arrayDePonteiros[0] = objeto.int;

In case this array is inside a class and as it will be only a reference it will be static, so I can use this array to refer to the value of each object of the other class, which will be recorded in future on an eeprom, and the moment I read the value on eeprom I can use the pointer to pass the value of eeprom to the object variable.

My current code is:

class Scenario {

public:
int byteInicial; // byte da eeprom
static int* link[6]; // atual array de ponteiros



Scenario(int byteI) // construtor da classe
{ 

byteInicial = byteI;
link[0] = &led1.fade;
}

In this case I get the error: Undefined Reference to `Scenario::link'. I’ve tried to use

Scenario::Scenario link [0] = &led1.fade;

However I get the error when trying to use it anyway, either printing on the serial or trying to write to eeprom. What would be the right way to do it?

1 answer

2

This problem occurs because variables qualified as static in classes/structures should be defined outside the class besides being declared within it. So somewhere in your cpp file that is associated with this class you should declare the array.

// Arquivo .h
class Scenario {
public:
    int byteInicial; // byte da eeprom
    static int* link[6]; // atual array de ponteiros

    Scenario(int byteI) // construtor da classe
    { 
        byteInicial = byteI;
        link[0] = &led1.fade;
    }
    // ...
};

// Arquivo .cpp
int * Scenario::link[6];

As for your code, do you really want to save only pointer to 1 object at a time as you are doing ? In that case wouldn’t it be better to use a normal pointer instead of an array of pointers ? These are questions that I think you should ask yourself.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.