想象下简单的式子:
if(yy == xx.getValue()) ...
//xx 和 yy的定义
X xx;
Y yy;
//Y定义
class Y
{
public:
Y();
~Y();
bool operator ==(const Y&) const;
//...
};
//X定义
class X
{
public:
X();
~X();
operator Y() const; //conversion运算符
X getValue();
//...
};
编译器会将第一句简单的式子展开成如下:
if(yy.operator == (xx.getValue().operator Y()))
这一切都是编译器根据class的隐含语意,对我们的代码所做的增胖处理。如果我们需要,我们可以明确的写那样的式子。
虽然程序的语意是正确的,但是会产生临时对象:
- 产生一个临时的class X object,放置getValue()的返回值:
X temp1 = xx.getValue();
- 产生一个临时class Y object,放置operator Y()的返回值:
Y temp1.operator Y();
- 产生一个临时的int object,放置equality(等号)运算符的返回值:
int temp3 = yy.operator == (temp2);
最后,适当的destructor将被施行于每一个临时的class object身上:
//C++ pseudo
//以下是条件if(yy == xx.getValue()) ...的转换
{
X temp1 = xx.getValue();
Y temp2 = temp1.operator();
int temp3 = yy.operator == (temp2);
if(temp3) ...
temp2.Y::~Y();
temp1.X::~X();
}
这就是C++的一件困难的事情:不太容易从程序源码看出表达式的复杂程度。