簡體   English   中英

訪問類成員的成員變量時,cpp程序掛起

[英]cpp program hanging when accessing member variable of a class member

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

}      

您正在定義一個局部變量alphabet並將一個元素push_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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM