vendredi 14 décembre 2018

Overloading issues with constructor in C++11

Not sure why this does not compile. Error, can't overload constructor. I am using C++11, as far as I understand this code should work. While the length constructor can't overload, the width one can, which I find strange.

Sample code:

#include <QCoreApplication>
#include <iostream>
using namespace std;

class Rectangle
{
private:
    double m_length = 1.0;          
    double m_width = 1.0;           
    const int magicNumber = 888;

public:
    Rectangle()
    {
        cout << "Rectangle()" << endl;
    }

    Rectangle(double length)    // ERROR, CAN'T OVERLOAD
        : m_length(length)   
    {
    }

    Rectangle(double width)     // FINE
        : m_width(width)  
    {
    }

    Rectangle(double length, double width)  // FINE
        : m_length(length), m_width(width)
    {
        cout << "Rectangle(double length, double width)" << endl;
    }

    void print()
    {
        std::cout << "length: " << m_length << ", width: " << m_width << '\n';
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //Rectangle y(2.0, 3.0);
    Rectangle y(2.0);

    return a.exec();
}

Aucun commentaire:

Enregistrer un commentaire