簡體   English   中英

Qt中的繼承不允許我引用?

[英]inheritance in Qt won't allow me to reference?

因此,II在Qt項目中有一個h文件和一個cpp文件。 我必須在頭文件中聲明一些qstrings,我想在我的cpp文件中引用它們,但是我似乎無法訪問它,有人可以解釋為什么或正確的方法嗎?

#ifndef PROFILE_H
#define PROFILE_H

#include <QMainWindow>
#include "login.h"
#include "searchnote.h"
#include "note.h"
#include <QDebug>

namespace Ui {
class Profile;    
}

class Profile : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_actionAdd_Note_triggered();

private:
    Ui::Profile *ui;

private:
    QString name;
    QString major;
    QString school;
    Note myNoteList;    
};

#endif // PROFILE_H


#include "profile.h"
#include "ui_profile.h"    

Profile::Profile(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Profile)
{
    ui->setupUi(this);
}

Profile::~Profile()
{
    delete ui;
}

void Profile::on_actionAdd_Note_triggered()
{
    SearchNote openSearch;          //will send us the searchNote gui
    openSearch.setModal(true);
    openSearch.exec();    
}

void myNoteListAdd(QString newName){
    myNoteList.add();                //the cpp file doesnt recognize this object        
}

myNoteListAdd是獨立函數, myNoteListProfile類的私有數據成員。 只有相同類的成員函數(通常也稱為方法)才能訪問這些私有數據成員

您可能希望myNoteListAdd成為Profile的成員函數,即

class Profile : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_actionAdd_Note_triggered();
    **void myNoteListAdd(QString newName);**
private:
    Ui::Profile *ui;

private:
    QString name;
    QString major;
    QString school;
    Note myNoteList;    
};

並實現為:

void Profile::myNoteListAdd(QString newName){
    myNoteList.add(newName);                // assuming you want to add newName to myNoteList
}

否則,您需要某種方式來訪問成員myNoteList,方法是將其公開或擁有一個getter成員。 無論哪種情況,都需要一個Profile實例來使用,即:

class Profile : public QMainWindow
{
    Q_OBJECT

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

   //either this:
    Note myPublicNoteList;   
    // or this 
    Note getNoteList() { return myNoteList; }

private slots:
    void on_actionAdd_Note_triggered();        
private:
    Ui::Profile *ui;

private:
    QString name;
    QString major;
    QString school;

};

然后在您的.cpp

void myNoteListAdd(QString newName)
{
  Profile p = new Profile(); // or some other mechanism to get a Profile
  //then either
  p.myPublicNoteList.add(newName);
  // or 
  p->getNoteList().add(newName);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM