0

I don't quite understand how overloading the assignment operator works. When I try to use the code below, I get the message: No viable overloaded '='. The situation is similar for the operator '+='. [Changed example]

#include <iostream>
#include <chrono>

using namespace std;

class clockSystem {
public:
  string& operator=(tm& local_tm);
// string& operator+=(tm& local_tm);
  string getTime();
};

string& clockSystem::operator=(tm& local_tm){
//string& clockSystem::operator+=(tm& local_tm){
  string time;
  time.append(to_string(local_tm.tm_hour) + ":" + to_string(local_tm.tm_min) + ":" + to_string(local_tm.tm_sec));
  return time;
}

string clockSystem::getTime(){
  string time;
  chrono::system_clock::time_point now = chrono::system_clock::now();
  time_t tt = chrono::system_clock::to_time_t(now);
  tm local_tm = *localtime(&tt);
  time = local_tm;
//  time += local_tm;
  return time;
};

int main() {
  clockSystem clock;
  cout << clock.getTime() << endl;
  return 0;
}

I know that '=' must be non-static but when I use the operator to '+=' and add an additional argument, everything works fine.

#include <iostream>
#include <chrono>

using namespace std;

class clockSystem {
public:
  string getTime();
};

void operator+=(string& time, tm& local_tm){
  time.append(to_string(local_tm.tm_hour) + ":" + to_string(local_tm.tm_min) + ":" + to_string(local_tm.tm_sec));
}

string clockSystem::getTime(){
  string time;
  chrono::system_clock::time_point now = chrono::system_clock::now();
  time_t tt = chrono::system_clock::to_time_t(now);
  tm local_tm = *localtime(&tt);
  time += local_tm;
  return time;
};

int main() {
  clockSystem clock;
  cout << clock.getTime() << endl;
  return 0;
}

Can someone explain to me? The target is to use '=', what can I change to make it work?

SQTX
  • 13
  • 3
  • 1
    What is `clockSystem`? Are you declaring the operator at global scope or at class scope? A [mcve] would be nice. – HolyBlackCat May 25 '22 at 22:17
  • 1
    Post real code. – Pete Becker May 25 '22 at 22:19
  • One of the requirements for a user-defined operator overload is that one of the arguments must be your own type (or dependent on your own type, e.g. `std::vector` is ok). You're violating that with `string& operator+=(string& time, tm& local_tm)`, where all operands are standard library types. It's a requirement of the library, not the language, so you have a chance of getting away with it, but.... – Ben Voigt May 25 '22 at 22:22
  • @HolyBlackCat I changed the example to a more readable, but the problem is the same. – SQTX May 25 '22 at 22:46
  • @BenVoigt I understand but why everything works after the presented change? – SQTX May 25 '22 at 22:51

0 Answers0