构造函数与析构函数

先来一张Google与nexus,加油啦!

nexus x

56b4534eda76f766b169dda9

用构造函数确保初始化

下面是一个带构造函数的类的简单例子

class X

{

int i;

public:

X(); //constructor

}

当一个对象被定义时:

void f()

{

X a;

}

此时a就好像是一个int:为这个对象分配内存,但是当程序执行到a的序列点时,构造函数自动调用,传递到构造函数的第一个参数(秘密)是this指针,也就是调用者一函数对象的地址,但对构造函数来说,this指针指向没有被初始化的内存块,构造函数的作用就是正确初始化该内存块。

也可以通过向构造函数传递参数,指定对象该如何创建或设定对象初始值。

用析构函数确保清除

class X

{

int i;

public:

X(); //constructor

~X();//destructor

}

当对象超过它的作用域时,编译器将自动调用析构函数。在对象的定义点处构造函数被调用。

下面说明了构造函数与析构函数的上述特征:

// constructer.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"

#include<iostream>

using namespace std;

class Tree

{

int height;

public:

Tree(int initialHeight);

~Tree();

void grow(int years);

void printsize();

};

Tree::Tree(int initialHeight)

{

height = initialHeight;

}

Tree::~Tree()

{

cout << "inside Tree destructor" << endl;

printsize();

}

void Tree::grow(int years)

{

height += years;

}

void Tree::printsize()

{

cout << "Tree height is" << height << endl;

}

int main()

{

cout << "before opening brace" << endl;

{

Tree t(12);

cout << "after Tree creation" << endl;

t.printsize();

t.grow(4);

cout << "before closing brace" << endl;

}

cout << "after closing brace" << endl;

system("pause");

return 0;

}

结果:

捕获

posted @ 2016-05-09 01:43  01Turing  阅读(168)  评论(0编辑  收藏  举报