简体   繁体   English

如何从另一个类读取结构成员

[英]How to read struct members from another class

I have a struct in my mainwindow class:我的主窗口类中有一个结构:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "dialog.h"
#include <QMainWindow>

namespace Ui {
  class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

  public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    struct properties{
      int ID = -1;
    };

    properties ret_func();
  private slots:
    void on_btn1_clicked();

  private:
    Ui::MainWindow *ui;
    properties _properties;
    Dialog *_dialog;
};

#endif // MAINWINDOW_H

I set value to it's memeber in mainwindow.cpp by clicking on btn1 :我通过单击btn1mainwindow.cpp中将值设置为它的成员:

MainWindow::properties MainWindow::ret_func()
{
  return _properties;
}

void MainWindow::on_btn1_clicked()
{
  _properties.ID = ui->lineEdit->text().toInt();
  qDebug()<<_properties.ID;
  _dialog->exec();
}

by clicking on btn1 another window is opened and I want to read the struct member value by clicking on btn2 .通过单击btn1将打开另一个窗口,我想通过单击btn2来读取结构成员值。 This is my code:这是我的代码:

void Dialog::on_btn2_clicked()
{
    qDebug()<<MainWindow::ret_func().ID;//->this line has error
}

Error:错误:

error: cannot call member function 'MainWindow::properties 
MainWindow::ret_func()' without object
 qDebug()<<MainWindow::ret_func().ID;
                                ^

I have read some threads having similar problems but couldn't find solution please help me我已经阅读了一些有类似问题的线程,但找不到解决方案,请帮助我

MainWindow::ret_func() is not a static member, this is why the compiler says error: cannot call member function .. without object MainWindow::ret_func()不是静态成员,这就是为什么编译器说error: cannot call member function .. without object

You need to have the instance of MainWindow to apply ret_fun on it.您需要拥有MainWindow的实例才能对其应用ret_fun

If you have only one MainWindow you can modify that class to be a singleton to be able to do MainWindow::instance().ret_func().ID;MainWindow::ret_func().ID;如果您只有一个MainWindow,您可以将该类修改为单例,以便能够执行MainWindow::instance().ret_func().ID;MainWindow::ret_func().ID;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM