![]() |
#2
wmf20142015-10-06 09:04
|

#include <iostream>
#include <string>
const std::string Wait_Message("Press any key to continue...");
// 複數類定義
class Complex
{
public:
Complex(double x, double y) : _x(x), _y(y)
{
++Create_Count;
std::cout << "Create[" << Create_Count << "]: (" << _x << ", " << _y << ")" << std::endl;
}
~Complex()
{
++Destroy_Count;
std::cout << "Destroy[" << Destroy_Count << "]:(" << _x << ", " << _y << ")" << std::endl;
}
friend Complex operator+(const Complex& a, const Complex& b)
{
// 此處形參是引用,不會創建對象,故看不到a、b的構造函數
return Complex(a._x + b._x, a._y + b._y);
}
private:
double _x; // 實部
double _y; // 虛部
static int Create_Count; // 構造計數器
static int Destroy_Count; // 析構計數器
};
int Complex::Create_Count = 0;
int Complex::Destroy_Count = 0;
void Pause(const std::string msg)
{
std::cout << std::endl << msg;
std::cin.get();
}
void Test(Complex& x)
{
// 形參是引用,無需複製,故x不會調用構造函數,此處x為調用處a+b所得的臨時對象
Complex a(11, 12); // 創建一個對象,將會調用構造函數,此對象在函數結束時銷毀,看到析構函數
Complex b(a + x); // 用a+x創建一個對象,將會調用構造函數,此對象在函數結束時銷毀,看到析構函數
}
int main(void)
{
Complex a(1, 2); // 創建一個對象,將會調用構造函數,此對象在程序結束後銷毀,看不到析構過程
Complex b(3, 4); // 創建一個對象,將會調用構造函數,此對象在程序結束後銷毀,看不到析構過程
Test(a + b); // 將a、b運算之後所得到的臨時對象以引用方式傳入一個子函數
Pause(Wait_Message);
return 0;
}
根據注釋描述,即知何以出現5次構造卻僅有3次析構。
運行結果:
只有本站会员才能查看附件,请 登录
[ 本帖最后由 TonyDeng 于 2015-10-6 11:27 编辑 ]