Simple operator overload = not working

I am in the process of changing the integer class (this is not the latest updated copy, but it works with -std=c++0x ). I ran into a little problem: a simple operator overload 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 is this not the whole operator= overload point? I changed the int part to template <typename T> , but that doesn't work either.

What am I missing?

+4
source share
2 answers

Not. You do not use the = operator at all; even if the = character is present, initialization is done only with the help of constructors. For this reason, some people prefer constructive type initialization:

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

So you need a constructor that can accept int . Remember to mark it explicit .

In addition, for example, an assignment operator must return a link.

+6
source
 integer a = 132; 

It is initialization. It calls the conversion constructor, not operator = .

 integer a; a = 132; 

should work, but it's better to define a constructor:

 integer(int rhs){} 

Also note that operator = should return by reference.

+4
source

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


All Articles