Home > database >  C code to overload the assignment operator does not work
C code to overload the assignment operator does not work

Time:10-21

I'm having some issues compiling the code I wrote which has a custom class with an overloaded =.

rnumber.hpp:

#include <string>

class rnumber {
public:
  std::string number;

  // I added this constructor in an edit
  rnumber(std::string s) { number = s; }

  void operator=(std::string s) { number = s; }
  bool operator==(std::string s) { return number == s; }
  friend std::ostream &operator<<(std::ostream &os, const rnumber n);
};

std::ostream &operator<<(std::ostream &os, const rnumber n) {
  os << n.number;
  return os;
}

main.cpp:

#include "rnumber.hpp"
#include <iostream>
#include <string>

int main() {
  rnumber a = "123";
}

For some reason, this does not compile with the error conversion from ‘const char [4]’ to non-scalar type ‘rnumber’ requested. This shouldn't be a problem, because rnumber has an overload for =. Why am I getting this error?

EDIT: Even after adding a constructor, it doesn't work.

CodePudding user response:

rnumber a = "123"; tries to initialize a with a const char*, but there is no constructor taking a const char*.

You need to implement this constructor as well:

  rnumber(const char *s) { number = s; }

There are other possibilities, mentioned on other answer and comments.

CodePudding user response:

The problem is that rnumber a = "123"; is initialization and not assignment so that the copy assignment operator= cannot be used.

There are 2 ways to solve this as shown below:

Method 1

Use the converting constructor rnumber::rnumber(std::string)

int main() {
  rnumber a("123"); //this uses the converting ctor
  
}

Method 2

Create the object and then do the assignment:

int main() {
  rnumber a("somestring"); //creates the object using converting ctor 
  a = "123";               //uses assignment operator 
}

CodePudding user response:

"abc" is not a std::string literal, it is a string literal, in particular it is a const char[4]. There is an implicit conversion from const char[4] to std::string, by one of it's constructors, and an implicit conversion from std::string to rnumber by the constructor you edited in, but you only get one implicit constructor per initialisation.

What you can do is explicitly construct the rnumber, and the std::string parameter can be implicitly constructed.

int main() {
  rnumber a { "123" };
}

CodePudding user response:

The problem's that I was using the wrong constructor.

rnumber(std::string s) { number = s; } is an std::string constructor, where the assignment rnumber a = "123"; is assigning a const char* to a.

Add another constructor rnumber(const char *s) { number = s; } to the header.

  •  Tags:  
  • c
  • Related