如何访问另一个类的价值在当前工人阶级

问题描述:

父类:parentClass.h如何访问另一个类的价值在当前工人阶级

class parentClass : public QWidget 
{ 
    Q_OBJECT 

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

} 

父类:parentClass.cpp

// accessing child 

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

子类:childClass.h

class childClass : public QWidget 
{ 
    Q_OBJECT 

public: 
    childClass(); 
} 

子类: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 
+1

请尝试创建一个[最小,完整,可验证的示例](http://*.com/help/mcve)向我们展示。 –

+2

childClass不会继承parentClass!如果你想访问parentClass中的值,你应该创建该类的一个实例。 – basslo

+0

我已经包含#include parentClass在子类 – pravin

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

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 parentClass: public QWidget 
{ 

Q_OBJECT 

public: 

static QString nextFollowUpDate; 

} 

然后做访问成员变量:

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

另外,如果你打算使用这个类很多,但不希望继续键入“父类::”在你的代码,你可以定义一个南协商了旁边的那类包括:

#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; 
}