Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple overloading of operator= not working

I'm in the process of modifying my integer class (that's not my most updated copy, but it works with -std=c++0x). I came across a slight problem: a simple operator overloading refuses to work no matter what I do. this code:

#include <deque>
#include <iostream>
#include <stdint.h>

class integer{
    private:
        std::deque <uint8_t> value;

    public:
        integer(){}

        integer operator=(int rhs){
            return *this;
        }
};

int main() {
        integer a = 132;        
        return 0;
}

gives me: error: conversion from ‘int’ to non-scalar type ‘integer’ requested, but isn't that the whole point of overloading operator=? I have changed the int part to template <typename T> but that doesn't work either.

What am I missing?

like image 488
calccrypto Avatar asked Dec 27 '22 04:12

calccrypto


1 Answers

No. You're not using the = operator at all there; even though the = symbol is present, initialisation is done only with constructors. Some people prefer construction-type initialisation for clarity for that reason:

T a = 1;    // ctor
T b(2);     // ctor
T c; c = 3; // ctor then op=

So, you need a constructor that can take int. Don't forget to mark it explicit.

Additionally, by the way, an assignment operator should return a reference.

like image 114
Lightness Races in Orbit Avatar answered Jan 09 '23 11:01

Lightness Races in Orbit