[英]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. 晚上好,我正在开发一个项目,要求我在一个.cpp文件中使用一个字符串变量,并在下一个.cpp文件中使用相同的字符串变量。 This is my patientdatabase.cpp:
这是我的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 每当我点击patientDatabase中提供的表格上的patientId时,此功能基本上会将窗口更改为IVBD,现在我需要在我的IVBD.cpp中使用字符串'value'
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. 您将在头文件中定义名为
value
的全局变量,并在定义时使用extern
关键字。 It means that there is a global value
variable that is created once and every .cpp file includes that header will use same variable. 这意味着有一个全局
value
变量被创建一次,每个.cpp文件都包含该标头将使用相同的变量。 Let me write an example. 让我写一个例子。
Think you have common.h
file defining your string value: 认为你有
common.h
文件定义你的字符串值:
extern std::string value;
And you have two different .cpp files they share that common value. 你有两个不同的.cpp文件,他们共享这个共同的价值。 In file1.cpp create that
value
. 在file1.cpp中创建该
value
。
file1.cpp: file1.cpp:
#include "common.h"
std::string value;
void fooInFile1() {
value = "Changed from fooInFile1!";
}
file2.cpp 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. 在此示例中,file1.cpp和file2.cpp正在影响相同的
value
变量。
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
. 在
on_tableView_view_activated
您应该发出一个信号并在IVBD.cpp
捕获它。
Using global variables doen't sound good, though it works! 使用全局变量听起来不太好,尽管它有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.