[英]Get member of parent struct
我創建了一個SSCE來更好地解釋這一點。
在一個類中,我有一個變量,一個結構和該結構的聲明。 在該結構中包含構造函數,變量,結構和該結構的聲明。 在struct內部是一個構造函數。
Mother > Daughter > GDaughter
aka class > struct > struct
mother.h
#ifndef MOTHER_H
#define MOTHER_H
#include <QSplitter>
class Mother : public QSplitter
{
Q_OBJECT
public:
Mother(int);
int age;
struct Daughter
{
Daughter();
int height1;
struct GDaughter
{
GDaughter();
};
GDaughter *kate;
};
Daughter *tina;
};
#endif // MOTHER_H
現在讓我們看一下構造函數/源代碼。 這是我的問題。
mother.cpp
#include "mother.h"
#include <QDebug>
Mother::Mother(int a)
{
age = a;
tina = new Daughter();
}
Mother::Daughter::Daughter()
{
qDebug() << age; //Not going to work... I get it. Daughter isnt a derived class
height1 = 10;
kate = new GDaughter();
}
Mother::Daughter::GDaughter::GDaughter()
{
qDebug() << height1; //Why not? The GDaughter instance is a member of Daughter!
}
qDebug()
兩個qDebug()
is not a type name, static, or enumerator
。
目標是動態創建“子”結構。 因此,父結構可能具有0個子結構,1個子結構,甚至100個子結構。 這就是為什么我使用結構而不是派生類的原因。 除了無法訪問“父”變量的問題外,此設置看起來可以正常工作。
無論如何,我將包括其他文件:
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mother.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mom = new Mother(50);
}
MainWindow::~MainWindow()
{
delete ui;
}
main.cpp中
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "mother.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
Mother *mom;
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
如果我誤解了如何進行此類操作,請告訴我。
謝謝你的時間。
回答后
在mother.h中,我添加了父指針:
struct Daughter
{
Daughter(Mother *p); //Here
int height1;
struct GDaughter
{
GDaughter(Daughter *p); //And here
};
GDaughter *kate;
};
然后在mother.cpp中,填寫所需的代碼:
Mother::Mother(int a)
{
age = a;
tina = new Daughter(this); //Here
}
Mother::Daughter::Daughter(Mother *m) //Here
{
qDebug() << m->age; //Here
height1 = 10;
kate = new GDaughter(this); //Here
}
Mother::Daughter::GDaughter::GDaughter(Daughter *d) //Here
{
qDebug() << d->height1; //Here
}
在嵌套對象中保持指向父類對象的指針(如果使用智能指針,則為std :: weak_ptr)。
explicit MainWindow(QWidget *parent = 0);
在這里看一下Qt代碼,您將指針傳遞給構造函數中的父對象,如果parent為nullptr,則意味着MainWindow沒有父對象,也可以保留指向MainWindow父對象的指針,然后將其static_cast到精確類
#include <iostream>
class A {
class B{
public:
B(A *p):parent(p) { parent->hello(); }
private:
A *parent;
};
public:
A() { b = new B(this); }
void hello() { std::cout << "hello world" << std::endl; }
private:
B *b;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.