Search code examples
c++qtprivate

Is it possible to pass more than 2 private members to a class?


I have a problem while compiling in my Qt code. I don't know why I can't pass more than two private members to a class. Here's the code:

In the header file(named wind.h)

 #ifndef WIND_H
 #define WIND_H

 #include <QApplication>
 #include <QWidget>
 #include <QPushButton>

class second : public QWidget
{
    public:
        second();

    private:
        QPushButton *bout1;
        QPushButton *bout2;
        QPushButton *bout3;
};
#endif // WIND_H

In the wind.cpp file

  #include "wind.h"

 second::second() :QWidget()
 {
    setFixedSize(700, 150);
    bout1 = new QPushButton("button1", this);
    bout2 = new QPushButton("button2", this);
    bout3 = new QPushButton("button3", this);
}

And the main.cpp be like

#include <QApplication>
#include "wind.h"


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    second sec;
    sec.show();

    return app.exec();
}

Actually,this code doesn"t compile and runs the debug,there is even a error in the debug but if I put this line in comment it works :

  //bout3 = new QPushButton("button3", this);

So why isn't it working when I pass more than 2 private members ? And how could I fix it ?

Thanks ! :)


Solution

  • Your code works as shown. For reference, here's a single file example:

    #include <QApplication>
    #include <QWidget>
    #include <QPushButton>
    
    class Second : public QWidget
    {
    public:
       Second();
    
    private:
       QPushButton *bout1;
       QPushButton *bout2;
       QPushButton *bout3;
    };
    
    Second::Second() : QWidget()
    {
       setFixedSize(700, 150);
       bout1 = new QPushButton("button1", this);
       bout2 = new QPushButton("button2", this);
       bout3 = new QPushButton("button3", this);
    }
    
    int main(int argc, char *argv[])
    {
       QApplication a(argc, argv);
       Second sec;
       sec.show();
       return a.exec();
    }
    

    You don't need to list the base class constructor explicitly on the initializer list if you don't pass it any parameters. You also don't need to allocate anything on the heap explicitly. So, this is in a little better style:

    #include <QApplication>
    #include <QWidget>
    #include <QPushButton>
    
    class Second : public QWidget
    {
       QPushButton bout1, bout2, bout3;
    public:
       Second();
    };
    
    Second::Second() :
       bout1("button1", this),
       bout2("button2", this),
       bout3("button3", this)
    {
       setFixedSize(700, 150);
    }
    
    int main(int argc, char *argv[])
    {
       QApplication a(argc, argv);
       Second sec;
       sec.show();
       return a.exec();
    }