A::operator int()
。我想我很清楚这里发生了什么。但我想更准确地了解标准如何支持这些电话?我知道这种(隐式)运算符是在复制初始化中调用的,这似乎不是这里的情况。
#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 =".
}