gpt4 book ai didi

c++ - QT C++中对全局变量的 undefined reference

转载 作者:行者123 更新时间:2023-12-02 09:53:24 24 4
gpt4 key购买 nike

我尝试将字符串值从mainwindow.cpp传递到userdetails.cpp。我曾经使用过全局变量。并且在程序运行时,它显示错误消息“对globelusername 的 undefined reference ”。 globelusername表示全局变量名称。代码中有什么错误?

主窗口

    #ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "register.h"
#include "userdetails.h"
//#include <QtSql>
//#include <QSqlDatabase>
//#include <QMessageBox>

extern QString globelusername;

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();

主窗口
    #include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);

ui ->loginusername->setPlaceholderText("Username");
ui ->loginpassword->setPlaceholderText("Password");
QString username = ui ->loginusername ->text();
QString globelusername = username;
return ;//
}

MainWindow::~MainWindow()
{
delete ui;

}

void MainWindow::on_pushButton_clicked()
{
//open new registration in new window
hide();
regist = new Register(this);
regist ->show();

}

void MainWindow::on_pushButton_2_clicked()
{
//database connection
.....

QString username = ui ->loginusername ->text();
QString password = ui ->loginpassword ->text();

if(db.open()){

//query create

QSqlQuery query(QSqlDatabase::database("MyConnect"));

query.prepare(QString("SELECT * FROM user_reg_elec WHERE username = :username AND password = :password"));

query.bindValue(":username", username);
query.bindValue(":password", password);

QString globelusername = username; //globlevariable
}

userdetails.cpp
#include "userdetails.h"
#include "ui_userdetails.h"
#include <QSqlError>
#include "mainwindow.h"

Userdetails::Userdetails(QWidget *parent) :
QDialog(parent),
ui(new Ui::Userdetails)

{
ui->setupUi(this);

}

Userdetails::~Userdetails()
{

}

void Userdetails::on_pushButton_4_clicked()
{

{
// database connection
........

QString abc = globelusername;

最佳答案

这条线

extern QString globelusername;

只是声明一个全局变量而没有定义它。

您必须在一个.cpp文件中定义它(例如在mainwindow.cpp中):
#include "mainwindow.h"
#include "ui_mainwindow.h"

QString globelusername;

// ...

关于c++ - QT C++中对全局变量的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62405599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com