#include <iostream>
#include <string>
using namespace std;
int main(){
string s1 = "ECE";
string s2 = "244";
// to concatenate them, we can simply add them
string s3 = s1 + s2;
}
We’ve just done an operator overloading with +
+ to add numbers+ operator with stringsclass complex{
private:
double real;
double img;
public:
// our first constructor... the default one
complex(){
real = 0;
img = 0;
}
// our second constructor, where user defines the values for Re and Im
complex(double r, double i){
real = r;
img = i;
}
}
int main(){
complex x(3, 4);
complex y(5, 6);
complex z;
// can I say the following?
z = x + y; // I'm calling the "+" operator
}
z = x + y, the + operator expects 2 numbers, but we’re trying to sum 2 objects+ operator know what to do when it is used to add two objects (complex numbers)complex complex::operator+(complex rhs){
complex result(real + rhs.real, img + rhs.img);
return res;
}
+ operatorcomplex number class)complex is the return typecomplex is the scopeoperator+ is the operator itself that I’m going to overloadz = x + y;
z = x.operator+(y);
constoperator+ should not change data members of the object
const