【问题标题】:How to read struct members from another class如何从另一个类中读取结构成员
【发布时间】:2019-01-05 09:08:48
【问题描述】:

我的主窗口类中有一个结构:

#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

我通过点击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();
}

通过单击btn1 打开另一个窗口,我想通过单击btn2 读取结构成员值。这是我的代码:

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

错误:

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

我已经阅读了一些有类似问题但找不到解决方案的主题 请帮帮我

【问题讨论】:

  • 欢迎来到 Stack Overflow!作为新用户,请拨打tour阅读How to Ask。关于您的问题,读者需要过滤的信息太多,使您的问题变得糟糕。请在此处发布之前从您的代码中提取minimal reproducible example

标签: c++ qt


【解决方案1】:

MainWindow::ret_func()不是静态成员,这就是为什么编译器说error: cannot call member function .. without object

您需要有 MainWindow 的实例才能在其上应用ret_fun

如果您只有一个 MainWindow,您可以将该类修改为 singleton 以便能够执行 MainWindow::instance().ret_func().ID;MainWindow::ret_func().ID;

【讨论】:

  • 感谢您的回复。但是您的回答让我更加困惑。我是新手,不知道什么是单例!在网上搜索但无法理解。您会编辑我的代码吗?我的英语不好也是另一个原因。
  • 单例是一个只有一个实例的类,一个通常名为 instance 的静态成员返回该实例。但我不知道您有多少 MainWindow 实例,以及它是否可以是 singleton
  • 没有别的办法吗?是否可以将'MainWindow::ret_func()'设为静态成员来消除错误?
  • @rezamoslemi 您还可以在您的类 Dialog 中添加一个方法,以在MainWindow::on_btn1_clicked() 中为其提供实例,例如在_dialog-&gt;exec(); 之前执行dialog_-&gt;setWindow(this);。但坦率地说,在全球范围内,你的做法很奇怪
  • @rezamoslemi 如果 'MainWindow::ret_func()' 是静态的,则无法访问非静态成员,您只需推动问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 2017-02-22
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多