hiyachen 2024-03-10 17:22 采纳率: 0%
浏览 183

QT在头文件定义结构体,在cpp文件报错was not declared in this scope

QT在头文件定义结构体,在cpp文件报错was not declared in this scope
头文件
class MainWindow : public QMainWindow
{
    Q_OBJECT
    typedef struct _UserInfo
    //struct UserInfo
    {
        QString id;
        QString name;
    } UserInfo;

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

cpp文件中:


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    bool dbOK = false;
   UserInfo userInfo;

最后一行UserInfo userInfo处报错:error: 'useInfo' was not declared in this scope
请教各位

  • 写回答

2条回答 默认 最新

  • 檀越@新空间 2024-03-10 17:22
    关注

    hiyachen 下午好🌅🌅🌅
    本答案参考ChatGPT-3.5

    这个错误是因为你在cpp文件中使用了未声明的结构体类型。在C++中,头文件中定义的结构体只在该头文件中可见,需要在cpp文件中重新声明结构体。

    解决方案如下:

    1. 在需要使用结构体的cpp文件中包含头文件。
    #include "mainwindow.h"
    
    1. 在cpp文件中重新声明结构体。
    struct _UserInfo
    {
        QString id;
        QString name;
    };
    
    1. 使用重新声明的结构体。
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        bool dbOK = false;
        _UserInfo userInfo;
        userInfo.id = "123";
        userInfo.name = "John";
    }
    

    这样就可以解决错误了。注意,这里重新声明的结构体名称为_UserInfo,与头文件中的UserInfo有所不同,保证了在cpp文件中的可见性。

    评论

报告相同问题?

问题事件

  • 创建了问题 3月10日