简体   繁体   中英

QT Creator accessing pointers to objects

Very new to QT but basically I have a class called object and on my GUI is a one button and one text browser. Now in my class object I have one private QString variable called name and its constructor assigns a value (QString) to the variable called name. The object class has one function called QString getName() const; which returns the name:

class object{

private:

    QString name;
public:

    object(QString name);

    QString getName()const;
};

Now in QT in my mainwindow.h file I put

public: 
    object *o; 

and then in the constructor:

object o2("Name");

o = &o2;

Now I want to call the function void MainWindow::on_pushButton_clicked() and all this function will do is set the text in the text browser to the name variable in my object (which would be "Name" btw) so inside the function I put ui->Console->setText(o->getName()); console being the name of my text browser- when i run the code and click the button its saying that Ive referenced memory and giving an error. Keep in mind I moved ui->Console->setText(o->getName()); to the constructor and it worked perfectly (obviously didnt work when the button was clicked but the text was put in the text browser) so what am I doing wrong here?

The pointer ( o ) outlives the object that it points to ( o2 ). One way to fix it is by allocating new memory for the object:

o = new object("Name");

And then you'll need to remember to delete that memory later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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