C ++ assignment operator and overload

I was wondering why the following code was compiled.

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

class Integer{
private:
    int i;
public:
    Integer(int value):i(value){}
    // unary or binary
    const Integer operator+(const Integer& rv){
        cout << "operator+"<< endl;
        return Integer(i + rv.i);
    }
    // Binary Operator
    Integer& operator+=(const Integer& rv){
        cout << "operator+=" << endl;
        i += rv.i;
        return *this;
    }
    ostream& operator<<(ostream& lv){
        lv << i;
        return lv;
    }
    friend ostream& operator<< (ostream& lv, Integer& rv);
};

ostream& operator<< (ostream& lv,Integer& rv){
    return lv << rv.i;
}

int main(){
    cout << "using operator overloading"<< endl;

    Integer c(0), a(4), b(5);
    Integer d = 8;
    c = a + b;
    cout << c << endl;
    cout << d << endl;
}

I do not understand why d = 8 is possible. D is a user-defined type. I did not overload the oeprator job for the Integer class. Is there a default overloaded operator?

+4
source share
3 answers

You have not declared a constructor Integer explicit, so it acts as an implicit conversion from intto Integer.

If you declare your constructor

explicit Integer(int value);

the compiler raises an error:

error: conversion from 'int to non-scalar type' Requested number

+8
source

Your constructor defines a conversion from int to Integer

Integer(int value):i(value){}
+2
source

, d = 8. d - .

, ctor.

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

class Integer{
private:
    int i;
public:
    Integer(int value):i(value){
        cout << "Integer(int) called with " << value << endl; 
    }
    // unary or binary
    const Integer operator+(const Integer& rv){
        cout << "operator+"<< endl;
        return Integer(i + rv.i);
    }
    // Binary Operator
    Integer& operator+=(const Integer& rv){
        cout << "operator+=" << endl;
        i += rv.i;
        return *this;
    }
    ostream& operator<<(ostream& lv){
        lv << i;
        return lv;
    }
    friend ostream& operator<< (ostream& lv, Integer& rv);
};

ostream& operator<< (ostream& lv,Integer& rv){
    return lv << rv.i;
}

int main(){
    Integer d = 8;
     cout << d << endl;
}

:

Integer(int) called with 8
8

Coliru's

The intended purpose of immediate 8 actually calls the explicit Integer(int) ctor call, which will be called with 8 as an argument,

+2
source

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


All Articles