[英]C++ operator overloading synthetic conversion
This example is from "Thinking in C++", I have one question regarding compiler synthesizing the operator conversion function. 该示例来自“ C ++的思考”,我对编译器综合运算符转换函数有一个疑问。
Question 题
When object of class Four is passed (in the function call f()), the overload operation () is called. 当传递第四个类的对象时(在函数调用f()中),将调用重载操作()。 But I am not able to make out the logic used (compiler synthesizes the operation call) by compiler to achieve this conversion.
但是我无法找出编译器用来实现此转换的逻辑(编译器合成操作调用)。
At max, I can expect explicit conversion behavior, like 最多,我可以期望有明确的转换行为,例如
1. obj3 = (Three)obj4; 1. obj3 =(Three)obj4;
2. obj3 = Three(obj4); 2. obj3 = Three(obj4);
3. obj3 = static_cast <Three
> (obj4); 3. obj3 = static_cast
<Three
>(obj4);
Now for any one of the above conversion - how does the compiler synthesize, 现在,对于上述任何一种转换-编译器如何进行合成,
(Three) obj4.operator()? (三)obj4.operator()?
May be I am missing some major point. 可能是我缺少一些要点。
Example 例
//: C12:Opconv.cpp
// Op overloading conversion
class Three {
int i;
public:
Three(int ii = 0, int = 0) : i(ii) {}
};
class Four {
int x;
public:
Four(int xx) : x(xx) {}
operator Three() const { return Three(x); }
};
void g(Three) {}
int main() {
Four four(1);
g(four);
g(1); // Calls Three(1,0)
} ///:~
First of all it is not operator()
which you have provided, it is operator Three
. 首先,不是您提供的
operator()
,而是operator Three
。 This operator tells the compiler how to convert an object of class Four
to an object of class Three
. 该运算符告诉编译器如何将
class Four
的对象转换为class Three
的对象。 In g(four)
call compiler is using this operator since the function g
is expecting an argument of type Three
. 在
g(four)
调用编译器使用此运算符,因为函数g
期望使用类型Three
的参数。 Since there is an conversion available compiler is using it. 由于存在转换,因此编译器正在使用它。 In the second case, since the constructor of
Three
is not declared as explicit
and it is possible to construct a object of class Three
using a single integer (using Three
constructor) compiler is using that constuctor to create an object of the class Three
so that function g
can be called. 在第二种情况下,由于构造
Three
未声明为explicit
,并且能够构造的对象class Three
使用单个整数(使用Three
构造)编译器是使用constuctor创建的目的class Three
使得可以调用函数g
。
First of all, class Four
does not contain an operator()
, but it does have an operator Three()
, which is a conversion operator. 首先,
class Four
不包含operator()
,但确实具有operator Three()
,它是一个转换操作符。
In the line 在行中
g(four);
the compiler needs to convert four
to an object of class Three
and synthesises a call to operator Three()
to perform that conversion. 编译器需要将
four
转换为class Three
的对象,并综合对operator Three()
的调用以执行该转换。 The synthesised conversion is equivalent to 合成的转换等于
g(four.operator Three());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.