如何在当前工作 class 中访问另一个 class 的值

How to access the value of another class in current working class

Parent class : parentClass.h

class parentClass : public QWidget
{
    Q_OBJECT

public:
    QString nextFollowUpDate;   //I want to access this variable from child class

}

Parent class : parentClass.cpp

// accessing child 

childClass*objcalender = new childClass();
objcalender->show();

Child class : childClass.h

class childClass : public QWidget
{
    Q_OBJECT

public:
    childClass();
}

Child class : childClass.cpp

#include parentClass .h

parentClass *myFollowUp = qobject_cast<parentClass*>(parent());

//object of myFollowUp is not created and program get terminated by showing exception 

parentClass->nextFollowUpDate = selectedDate;   //can not access this variable

两件事。 首先,如果你想从另一个 class 访问 class 的成员函数或变量,你必须创建一个你想要访问的 class 的对象,然后只需使用“->”要么 ”。”访问它。 像这样:

ParentClass* parentObjPtr = new ParentClass(); //not mandatory to use the new() operator, but it has always better to reserve the memory space
parentObjPtr->varName = "hello";
//OR
ParentClass parentObj = new ParentClass();
parentObj.functionName = "hello";

但如果出于某种原因您不打算创建 class 的对象,您可以随时创建您想要访问的成员 "static":

class parentClass: public QWidget
{

Q_OBJECT

public:

static QString nextFollowUpDate;

}

然后执行此操作以访问该成员变量:

ParentClass::nextFollowUpDate = "hello";
cout << "Content of nextFollowUpDate: " << ParentClass::nextFollowUpdate << endl;

此外,如果您打算经常使用 class 但不想在代码中继续输入 "ParentClass::",您可以在您的 class 旁边定义一个名称空间包括:

#include "ParentClass.h"
using namespace ParentClass;
----ETC----
----ETC----

int main(){
nextFollowUpDate = "hello"; //because we defined a namespace for that class you can ommit the "ParentClass::"
cout<<nextFollowUpDate<<endl;
}