I am trying to understand overloading operators in c++. I've written some code below trying to overload the =
operator. However, it doesn't work correctly and I am wondering why now.
I've followed the example that is provided here for the +
operator.
#include <iostream>
using namespace std;
class Test {
private:
int id;
string name;
public:
Test(): id(0), name(""){
}
Test(int id, string name): id(id), name(name) {
}
void print() {
cout << id << ":" << name << endl;
}
Test operator=( Test &other) {
Test test;
cout << "Assignment running" << endl;
test.id =other.id;
test.name =other.name;
return test;
}
};
int main() {
Test test1(10, "Mike");
cout << "Print Test1" << endl;
test1.print();
Test test2;
test2.operator=(test1);
cout << "Print Test2" << endl;
test2.print();
cout << endl;
}