【发布时间】:2016-02-24 08:51:32
【问题描述】:
我创建了一个 SSCE 来更好地解释这一点。
在一个类中,我有一个变量、一个结构和一个结构的声明。在该结构中是构造函数、变量、结构和该结构的声明。在那个结构里面是一个构造函数。
Mother > Daughter > GDaughter又名class > struct > struct也是如此
妈妈.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() 两条线都抛出 is not a type name, static, or enumerator。
目标是动态创建“子”结构。所以一个父结构可能有 0 个子结构,1 个子结构,甚至 100 个子结构。这就是我使用结构而不是派生类的原因。除了无法访问“父”变量的问题之外,此设置看起来可行。
无论如何我都会包含其他文件:
主窗口.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();
}
主窗口.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
}
【问题讨论】:
-
您的设计令人困惑。
age是母亲的年龄还是女儿的年龄?如果您只使用函数和私有成员变量将值传递给其他类,那就更好了。似乎也没有理由使用嵌套结构。 -
我知道,这是一个用于测试不同事物的 SSCE。这不是我的实际程序。母亲、女儿和女儿只是更简单的查看嵌套的方式......没关系......
-
我明白了。我被你为这个特定例子选择的名字吓坏了。