Why is this transformation happening?

#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+ca; temp.b=b+cb; 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 an operator of the type t3=t1+2; where 2 not an object?

+4
source share
7 answers

The compiler sees that you are calling operator+(test) and is trying to implicitly convert 2 to test using the test(int i,int j=0) constructor test(int i,int j=0) .

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 will generate a compiler error, because 2 cannot be implicitly converted to test . You will need to change the expression to t1 + test(2) .

+7
source

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 step, test operator +(test c) called.

+2
source

There is a binary operator+ that accepts two operands of type test . Moreover, test implicitly constructive from int through the constructor test(int, int = 0) . Putting the two together, t1 + 2 becomes t1 + test(2, 0) .

To prohibit this silent conversion (which can sometimes cause very amazing conversion chains), declare your constructors that take one single argument as explicit: explicit test(int, int = 0) .

+2
source

Because test(int i, int j = 0) not marked explicitly.

Therefore, t1 + 2 interpreted as t1.operator+(2) , which itself is interpreted as t1.operator+(test(2)) (implicit conversion).

If you mark the constructor as explicit , an error will occur (at compile time), stating that 2 cannot be converted to test or that operator+ does not match.

+1
source

In short, since C ++ includes operator overloading, the ability to define custom operator implementations for user types. The operator+() function shown above is how you define the + operator for type test . When the compiler sees an expression in which + is applied to the test object, it searches for operator+ defined in test (or a form with two arguments defined as a global function with the first argument of type test or test& .) Then it calls the function, possibly after converting another argument.

0
source

Because your constructor test(int i,int j=0) introduces a user-defined conversion from int to test .

0
source

The compiler creates an object of type Test using its constructor.

  t3 = t1 + test(2); 
0
source

All Articles