zxin
2025-05-14 d5fad640fb749ab6626cbf68ba2b7cdc1fd058f7
提交
2个文件已添加
118 ■■■■■ 已修改文件
Test/errorexample.cpp 105 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Test/errorexample.h 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Test/errorexample.cpp
New file
@@ -0,0 +1,105 @@
#include "errorexample.h"
#include <QLabel>
errorexample::errorexample() {
  // 1.未包含必要的头文件
  // 错误:缺少 #include <QLabel>
  QLabel label("Hello");  // 编译错误:'QLabel' was not declared in this scope
  label.show();
  // 2.未初始化指针
  QLabel *label4;
  label4->setText("Hello");  // 错误:使用未初始化的指针
  // 修复:初始化指针
  QLabel *label5 = new QLabel;
  // 3.父对象管理不当导致内存泄露
  QLabel *label1 = new QLabel("Memory Leak");
  label1->show();
  // 正确做法:设置父对象,Qt会自动管理内存
  QWidget *parent = new QWidget;
  QLabel *managedLabel = new QLabel("Managed", parent);
  // 4.使用已删除的对象
  QLabel *label2 = new QLabel("Delete Me");
  delete label2;
  // 错误:访问已删除的对象
  label2->setText("Oops");  // 未定义行为
  // 5.字符串编码问题
  QLabel *label3 = new QLabel;
  // 错误:硬编码非ASCII字符串
  label3->setText("中文文本");  // 可能显示乱码,取决于源文件编码
  // 正确做法:使用tr()进行翻译
  label3->setText(tr("中文文本"));
  // 6.容器越界访问
  QList<int> list = {1, 2, 3};
  // 错误:越界访问
  int value = list[3];  // 索引最大为2
  // 正确做法:使用at()并检查边界
  if (list.size() > 3) {
    int safeValue = list.at(3);  // at()会在越界时抛出异常
  }
  // 7.缺失终止条件的For循环
  for (int i = 0;; i++) {  // 错误:无终止条件
                           //循环体
  }
  // 正确写法:
  for (int i = 0; i < 10; i++) {  // 添加终止条件
                                  //循环体
  }
  // 8.误用 = 代替 ==
  if (x = 5) {  // 误将赋值操作当作比较,条件始终为 true(除非 x 是布尔类型)
                // ...
  }
  // 9.事件处理未调用基类实现
  void CustomWidget::paintEvent(QPaintEvent * event) {
    // 错误:未调用基类实现
    QPainter painter(this);
    // 缺少:QWidget::paintEvent(event);
  }
  // 10.信号槽参数不匹配
  // 错误:信号参数与槽参数类型不匹配
  connect(sender, &Sender::valueChanged(int), receiver,
          &Receiver::updateValue(QString));
  // 修复:确保参数类型一致
  connect(sender, &Sender::valueChanged(int), receiver,
          &Receiver::updateValue(int));
  // 11.未实现纯虚函数
  class MyInterface {
   public:
    virtual void pureVirtual() = 0;
  };
  class MyClass : public MyInterface {
    // 错误:未实现纯虚函数
  };
  // 修复:实现纯虚函数
  void MyClass::pureVirtual() { /* 实现 */
  }
  // 12.未正确实现拷贝构造函数
  class MyClass1 {
   public:
    QWidget *widget;
    MyClass1(const MyClass1 &other) { widget = other.widget; }  // 错误:浅拷贝
  };
  // 修复:深拷贝或禁用拷贝构造函数
  MyClass1(const MyClass1 &other) = delete;
}
Test/errorexample.h
New file
@@ -0,0 +1,13 @@
#ifndef ERROREXAMPLE_H
#define ERROREXAMPLE_H
#include <QObject>
class errorexample
{
    Q_OBJECT
public:
    errorexample();
};
#endif // ERROREXAMPLE_H