C ++ class with several constructors - File header and cpp

2

I have a C ++ class where I have two constructors. In the minhaclasse.h file:

public:
  MinhaClasse(int x1);
  MinhaClasse(int x1, int x2);

Then in the minhaclasse.cpp file I usually create the builders that I declared there in the header. So far so good. The problem now happens in my Main class. In the header file of the Main class, I want to declare within public:

public:
  MinhaClasse classe;

But if I run the project at this point, the above line gives error, saying there is an ambiguity, because as I did not initialize the class object, and it does not know which constructor to use. The only way I did that worked was to not declare the object inside the Header, and let me declare it whole already inside the CPP:

 MinhaClasse classe = MinhaClasse(5);

Then I come to my question: if the MinhaClasse class has two constructors, it has some "bad luck" to be able, in my Main class, to declare the 'class' object inside the Header, without initializing it, or in this case I will really need to not create the object in the header and let it declare it completely inside the CPP ??

Calculator file.h

#ifndef CALCULADORA_H
#define CALCULADORA_H
class Calculadora
{
public:
    Calculadora(int x=0);
    Calculadora(int x=0, int y=0);
};
#endif // CALCULADORA_H

Calculator file.cpp:

#include "calculadora.h"
#include "qdebug.h"
Calculadora::Calculadora(int x)
{
    qDebug() << x;
}
Calculadora::Calculadora(int x, int y)
{
    qDebug() << x+y;
}

And in mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

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

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:

private:
    Ui::MainWindow *ui;
    Calculadora calc; // aqui dá o erro!!!!
};

#endif // MAINWINDOW_H
    
asked by anonymous 25.06.2015 / 16:19

1 answer

2

Instead of "directly" executing the class call with:

private:
    Ui::MainWindow *ui;
    Calculadora calc; // aqui dá o erro!!!!

Do this:

private:
    Ui::MainWindow *ui;
    Calculadora *calc;

And in CPP call it like this:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    calc = new Calculadora();
}

Read more at:

Error call of overloaded is ambiguous

What happens is that when you try to set default parameters, it can not decide which one to use.

Instead of this:

public:
    Calculadora(int x=0);
    Calculadora(int x=0, int y=0);

Do this:

public:
    Calculadora(int x=0);
    Calculadora(int x, int y);
    
26.06.2015 / 00:42