标签:
if (yy == xx.getValue())
// ... 其中xx和yy定义为:X xx; Y yy;class Y的定义为:
class Y {
public:
Y();
~Y();
bool operator==(const Y &) const;
}; class X定义为:class X {
public:
X();
~X();
operator Y() const; // conversion运算符
X getValue();
}; 首先决定equality运算符所参考到的真正实体.在这个例子中,它将被决议(resolved)为"被overloaded的Y成员实体".下面是该式子的第一次转换:// resolution of intended operator
if (yy.operator==(xx.getValue()))
// ... Y的equality运算符需要一个类型为Y的参数,然而getValue()传回的确实一个类型为X的object,若非有什么方法可以把一个X object转换为一个Y object,那么这个式子就算错.本例中X提供一个conversion,把一个X object转换为一个Y object.它必须施行于getValue()的返回值上.下面是该式子的第二次转换:// conversion of getValue()'s return value
if (yy.operator==(xx.getValue().operator Y()))
// ... 到目前为止所发生的一切都是编译器根据 class 的隐含语意,对程序代码所做的"增胖"操作.如果需要,也可以明确地写出那样的式子.X temp1 = xx.getValue();产生一个临时的 class Y object,放置operator Y()的返回值:
Y temp2 = temp1.operator Y();产生一个临时的 int object,放置equality运算符的返回值:
int temp3 = yy.operator==(temp2);最后,适当的destructor将被施行于每一个临时性的 class object上,这导致式子被转换为以下形式:
// C++伪代码:以下是条件句 if (yy == xx.getValue()) ... 的转换
{
X temp1 = xx.getValue();
Y temp2 = temp1.operator Y();
int temp3 = yy.operator==(temp2);
if (temp3)
// ...
temp2.Y::~Y();
temp1.X::~X();
} 似乎不少,这是C++的一件困难事情:不太容易从程序代码看出表达式的复杂度.本章看一看执行期所发生的一些转换.版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/yiranant/article/details/47687473