cpp程序在访问类成员的成员变量时挂起

时间:2018-06-30 03:04:29

标签: c++ arduino teensy

使用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() {

}      

1 个答案:

答案 0 :(得分: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");
}