#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 the 2
to a test
successfully using your test(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 because 2
cannot be implicitly converted to test
. You would need to change the expression to t1 + test(2)
.
Because test(int i,int j=0)
is a constructor that takes one or two arguments, so a test
object is created from 2
. In the next stage test operator +(test c)
is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With