简体   繁体   中英

C++/Arduino Implementation of array

I have a problem in the use of an array of pointers, need to create an array of pointers that refer to an integer value of each object from another class.

example:

arrayOfPointers[0] = object.int;

In case this array is within a class and how it is just a reference it will be static, so I can use this array to refer to the value of each object of another class, which will be recorded in a future eeprom, and the moment I is read the value in eeprom I can use the pointer to pass the value of the eeprom for the object variable.

My current code is:

class Scenario {

public:
int byte; // byte of the eeprom
static int* link[6]; // array of pointers



Scenario(int byteI) // constructor of the class
{ 

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

In this case I get the error: undefined reference to `Scenario :: link '. I've tried using

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

But I got the error when trying to use it in any way, either in serial printing, or trying to write in eeprom. What would be the correct way to do this?

Your line static int* link[6]; // array of pointers static int* link[6]; // array of pointers inside your class definition is only a declaration because it is static. You need to ad a definition outside the class in a source file (not a header): int* Scenario::link[6];

Something like this:

struct led
{
    int fade;
};

led led1;

// put this in a header file Scenario.h
class Scenario
{

public:
    int byte; // byte of the eeprom
    static int* link[6]; // array of pointers (DECLARATION)

    Scenario(int byteI) // constructor of the class
    {

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

// put this in a source file Scenario.cpp
int* Scenario::link[6]; // (DEFINITION)

// make sure you link Scenario.o along with your main object file
int main()
{
    Scenario s(4);
}

Static member variables always need to be defined in the code file.

Insert Scenario::link initialization in the code file after the class definition:

int* Scenario::link[6] = {NULL};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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