C++ 在下面的代码中,标准如何规定对A::operator int()的调用?
C++ 在下面的代码中,标准如何规定对A::operator int()的调用?,c++,c++11,language-lawyer,C++,C++11,Language Lawyer,A::operator int()在下面的代码中根据程序中的注释进行调用。我想我对这里发生的事情有很好的感觉。但我想更准确地知道标准是如何支持这些调用的?我知道这种(隐式)操作符是在副本初始化中调用的,这里的情况似乎不是这样 #include <iostream> class A { int i; public: A(int j) : i(j){ std::cout << "constructor\n"; } A& operator=(
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 =".
}
#包括
甲级{
int i;
公众:
A(intj):i(j){std::cout对于每个“函数调用”,编译器都会生成一个可以通过一次“用户转换”(包括构造函数和转换运算符)实现的函数列表,如果有一个匹配,它就会调用它。否则它就有一个编译器错误。这里的问题是什么?你期望会发生什么?另外,我在注释中看到至少一个错误的语句,其中构造了c
。啊,(a-b)*c
行确实遇到了一个更复杂的情况,即某些函数调用“更好”与其他函数相比,我忽略了这一点。因此,你在问编译器如何决定哪些函数是“最好的”匹配一个参数集?这个答案实际上令人惊讶地复杂:PIt将花费太长的时间来列举标准中解释您给出的表达式所需的所有段落。《C++11》中的§13.3涉及重载解析,所以从这里开始。“我知道这种(隐式的)运算符在复制初始化中被调用,这里的情况似乎不是这样。“参数传递(按值)调用复制初始化。[dcl.init]/14