Quantcast
Channel: Visual C forum
Viewing all articles
Browse latest Browse all 15302

What does the Standard say about the use of operator int() in the code below?

$
0
0

I already know from here that § 13.3.1.2/2 answers my question about the invocation of operator int() in the expression 

c = (a - b) * c;

below. But I still don't have a quote from the Standard justifying the use of the operator int() in the two expressions

std::cout << c << '\n';

in the code below.

#include <iostream>
class A {
   int i;
public:
   A(int j) : i(j){ std::cout << "constructor\n";  }
   A& operator=(int j) { std::cout << "operator =\n"; i = j; return *this; }
   A& operator+=(const A& rhs) { i += rhs.i; return *this; }
   const A operator+(const A& rhs) const { return A(*this) += rhs; }
   A& operator-=(const A& rhs) { i -= rhs.i; return *this; }
   const A operator-(const A& rhs) const { return A(*this) -= rhs; }
   operator int() const { std::cout << "operator int()\n"; return i; }
};
int main()
{
   A a(1);			// Invokes constructor A(int), printing "constructor"
   A b(2);		// Idem
   A c = a + b;			// Invokes a.operator+(b) followed by a call to the default copy constructor which copies
    				// the object referenced by the return of a + b into c.
   std::cout << c << '\n';	// operator int() is called to convert the object c into an int, printing "operator int()"
    				// followed by the number 3.
    c = a - b;		// Invokes a.operator-(b) followed by a call to the default assignment operator which// copies the object referenced by the return of a - b into c.
    std::cout << c << '\n';	// operator int() is called to convert the object c into an int, printing "operator int()"
    				// followed by the number -1.
    c = (a - b) * c;		// Invokes a.operator-(b) followed by two calls to operator int(), one to convert the
    				// result of a - b into an int and another to convert c into an int. Finally the special
    				// assignment operator, operator=(int) is called to assign the int resultant from the
    				// expression (a - b) * c to the object c, printing "operator =".
}



Viewing all articles
Browse latest Browse all 15302


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>