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?