简体   繁体   中英

Transferring a string from one .cpp file to another

Good evening, I working on a project that requires me to use a string variable in one .cpp file and same string variable in the next .cpp file. This is my patientdatabase.cpp:

void patientDatabase::on_tableView_view_activated(const QModelIndex &index)
{
 QString value = ui->tableView_view->model()->data(index).toString();
 patientR.connOpen();
 QSqlQuery qry;
 qry.prepare("select * from imageTable where PatientId = '"+value+"'");
if (qry.exec()){
    IVDB *x = new IVDB;
    x->show();
}

This function basically changes windows to IVBD whenever I click on patientId on the table provided in my patientDatabase and now I need the string 'value' in my IVBD.cpp

QSqlQuery *qry = new QSqlQuery(registration.db);
qry->prepare("select * from imageTable where PatientId ='"+value+"'");    // this string 'value; is from the last .cpp file

I dont want to use global variables but stuck here and not sure how to approach it.

If you don't want to use global variable it is better share your classes and we can think with your current design. Otherwise there is a global approach below.

You will define a global variable named value in a header file and you will use extern keyword while defining. It means that there is a global value variable that is created once and every .cpp file includes that header will use same variable. Let me write an example.

Think you have common.h file defining your string value:

extern std::string value;

And you have two different .cpp files they share that common value. In file1.cpp create that value .

file1.cpp:

#include "common.h"

std::string value;

void fooInFile1() {
    value = "Changed from fooInFile1!";
}

file2.cpp

#include "common.h"

void fooInFile2() {
    value = "Changed from fooInFile2!";
}

In this example file1.cpp and file2.cpp are affecting the same value variable.

The best solution I can think of would be using signals and slots . In on_tableView_view_activated you should emit a signal and catch it in IVBD.cpp .

Using global variables doen't sound good, though it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM