#include<iostream>
using namespace std;
class test
{
int a, b;
public:
test() {
a=4; b=5;
}
test(int i,int j=0) {
a=i; b=j;
}
test operator +(test c) {
test temp;
temp.a=a+c.a;
temp.b=b+c.b;
return temp;
}
void print() {
cout << a << b;
}
};
int main() {
test t1, t2(2,3), t3;
t3 = t1+2;
t3.print();
return 0;
}
How can the compiler accept a statement like t3=t1+2; where 2 is not an object?
The compiler sees you are invoking
operator+(test)and attempts to implicitly convert the2to atestsuccessfully using yourtest(int i,int j=0)constructor.If you want to make the conversion explicit, you must change the constructor to
explicit test(int i, int j=0). In this case, your code would generate a compiler error because2cannot be implicitly converted totest. You would need to change the expression tot1 + test(2).