1

使用 Teensy 3.2,我的程序挂在下面指出的部分。我不知道如何访问glyph。如果我注释掉该//hangs here行,我可以看到所有行都打印到我的 Arduino 串行监视器上。

#include <vector>
#include <Arduino.h>

class Letter {
    public:
        String glyph = "a";
};

class Language {
    public:
        Language();
        std::vector <Letter> alphabet;
};

Language::Language(){
    std::vector <Letter> alphabet;
    Letter symbol = Letter();
    alphabet.push_back(symbol);
    delay(2000);
    Serial.println("hello world");//prints in the arduino monitor
    Serial.println(this->alphabet[0].glyph);//hangs here
    Serial.println("line of interest executed");//runs only if line above is commented out
}

void setup() {
    Serial.begin(9600);
    Language english = Language();
}

void loop() {

}      
4

1 回答 1

2

您正在定义一个局部变量alphabetpush_back一个元素。这与成员变量无关alphabet。然后this->alphabet[0].glyph导致UB,成员变量alphabet还是空的。

你可能想要

Language::Language() {

    Letter symbol = Letter();
    this->alphabet.push_back(symbol);
    // or just alphabet.push_back(symbol); 

    delay(2000);
    Serial.println("hello world");//prints in the arduino monitor
    Serial.println(this->alphabet[0].glyph);
    Serial.println("line of interest executed");
}
于 2018-06-30T03:08:19.163 回答