Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

c++ - Managing an array of objects issue on Arduino

I am trying to manage an array of objects (this is a simplified version). When I create the objects statically, they display correctly. When I build them dynamically the results are as if I did not initialize them. The following test shows both results. Any thoughts?

class Student {
public:
    String name;
    int rollno;

    Student() {}

    Student(String x, int y) {
        name = x;
        rollno = y;
    }

    void printDetails() {
        Serial.print(rollno); Serial.print(" - "); Serial.println(name);
    }
};

    //declare array with specific size
    Student statics[5];
    Student dynamics[5];

void setup()
{
    //Open serial port at 115200 baud
    Serial.begin(115200);

    //Wait until the serial port has opened
    while (!Serial) delay(1);
    Serial.println("setup static");
    //assign objects
    statics[0] = Student("Ram", 5);
    statics[1] = Student("Alex", 1);
    statics[2] = Student("Lesha", 4);
    statics[3] = Student("Emily", 3);
    statics[4] = Student("Anita", 2);

    for (int i = 0; i < 5; i++) {
        statics[i].printDetails();
    }
    Serial.println("setup dynamic");

    //assign objects
    for (int i = 0; i > sizeof(dynamics); i++) {
        String name = "Name-" + String(i);
        dynamics[i] = Student(name, i);
    }
    for (int i = 0; i < 5; i++) {
        dynamics[i].printDetails();
    }
}

// Add the main program code into the continuous loop() function
void loop()
{
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to replace the > operator with < in the for loop.

 //assign objects
for (int i = 0; i < sizeof(dynamics); i++) {
    String name = "Name-" + String(i);
    dynamics[i] = Student(name, i);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...