cpp 程序在访问 class 成员的成员变量时挂起
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");
}
使用 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");
}