这是我检查笔记本电脑电池状态的代码。 我没有做到这一点,因为编译器给我一个关于switch案例的错误:
UPower *u = new UPower(this);
Battery *b;
foreach (Battery *bat, *u->batteries()) {
b = u->batteries()->value(bat->path());
}
ui->batteryProg->setValue(b->percentage());
switch( b->state() ) {
case Battery::FullyCharged:
ui->batteryStatus->setText( tr( "Full" ) );
break;
case Battery::Discharging:
ui->batteryStatus->setText( tr( "Discharging" ) );
break;
case Battery::Charging:
ui->batteryStatus->setText( tr( "Charging" ) );
break;
default:
ui->batteryStatus->setText( tr( "No Battery" ) );
break;
}
ui->batteryframe->setVisible(true);
这是编译过程输出的错误:
make: *** [Makefile:2028: corebox.o] Error 1
make: *** Waiting for unfinished jobs....
coreaction/coreaction.cpp: In member function 'void
coreaction::batteryCheck()':
coreaction/coreaction.cpp:114:25: warning: 'b' may be used
uninitialized in this function [-Wmaybe-uninitialized]
switch( b->state() ) {
~~~~~~~~^~
==> ERROR: A failure occurred in build().
Aborting...
我做错了什么?
答案 0 :(得分:2)
这是重要的部分:
coreaction/coreaction.cpp:114:25: warning: 'b' may be used
uninitialized in this function [-Wmaybe-uninitialized]
switch( b->state() ) {
~~~~~~~~^~
它声明b可以未初始化使用,如果循环为空则会为真,因此b永远不会被设置。
foreach (Battery *bat, *u->batteries()) {
b = u->batteries()->value(bat->path());
}
希望有所帮助。 解决方案是在将switch语句初始化为nullptr之后在switch语句之前测试b。
这是重要的部分,nullptr和未初始化的指针之间存在差异。
Battery* b = nullptr; // nullptr
Battery* b; // uninitialized
答案 1 :(得分:1)
溶液
Battery *b = nullptr;
foreach (Battery *bat, *u->batteries()) {
b = u->batteries()->value(bat->path());
}
if (!b)
return;