C ++ Default Constructors

I get a compilation error with the following code:

main.cpp: In function âint main()â:
main.cpp:38: error: no matching function for call to âComplex::Complex(Complex)â
main.cpp:22: note: candidates are: Complex::Complex(Complex&)
main.cpp:15: note:                 Complex::Complex(double, double)

But when I change the copy constructor argument type to const Complex &, it works. I thought that the default constructor would be called using 2 Complex :: Complex (2.0, 0.0), and then a copy constructor would be created to create with a copy of Complex (2.0. 0). Isn't that right?

#include <iostream>
using namespace std;

class Complex {
        double re;
        double im;

public:
        Complex(double re=0, double im=0);
        Complex(Complex& c);
        ~Complex() {};
        void print();
};

Complex::Complex(double re, double im)
{
        cout << "Constructor called with " << re << " " << im << endl;
        this->re = re;
        this->im = im;
}

Complex::Complex(Complex &c)
{
        cout << "Copy constructor called " << endl;
        re = c.re;
        im = c.im;
}


void Complex::print()
{
        cout << "real = " << re << endl;
        cout << "imaginary = " << im << endl;
}

int main()
{
        Complex a = 2;
        a.print();
        Complex b = a;
        b.print();
}
+3
source share
4 answers

When you write

Complex a = 2;

the compiler will not directly invoke the constructor Complex, using 0 as the default argument for the assembly a, but instead it will consider whether it can "convert" 2 to Complex.

, Complex(re,im) , explicit, a.

"" . , Complex(re,im), , ++ .

, , a, 2.

const, a, , .

a Complex a(2), .

, , , Complex a = ... , , , . , , , const, , a ( - - ). , .

+9

++ const , const, . , const, , Complex&.

+1

&, . , .

const, , . :

Complex::Complex(const Complex &c)
{
        cout << "Copy constructor called " << endl;
        re = c.re;
        im = c.im;
        c.im = 'something'; // This would not work
}

,
.

+1

, :

Complex::Complex(Complex &c)

const, , , , . , , Complex , !

, , Complex const:

Complex::Complex(const Complex &c)

, const, .

, , , . , , , . " ", , , ( ). , , , , .

, Complex , . <complex> complex<T> .

+1

Source: https://habr.com/ru/post/1789093/


All Articles