如何访问当前工作类

时间:2017-03-14 10:23:20

标签: c++ qt qt-creator qwidget qdialog

父类: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 个答案:

答案 0 :(得分:0)

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

def to_csv(s):
  s = s.split(',')
  s = [t.strip() for t in s]
  return s

def csv_reader(dicts):
  for d in dicts:
    d['csv'] = to_csv(d['line'])
    yield d

但是如果由于某种原因你没有计划创建该类的对象,你总是可以让你想要访问的成员“静态”:

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 ::”,则可以在包含的类旁边定义该类的命名空间:

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