类Class(二):构造函数(constructors)

 构造函数(constructors)

 

对象(object)在生成过程中通常需要初始化变量或分配动态内存,以便我们能够操作,或防止在执行过程中返回意外结果。

例如,在前面的例子 类Class(一) 中,如果我们在调用函数 set_values( ) 之前就调用了函数 area(),将会产生什么样的结果呢?

可能会是一个不确定的值,因为成员 width 和 height 还没有被赋于任何值。

 

为了避免这种情况发生,一个 class 可以包含一个特殊的函数:构造函数 constructor,它可以通过声明一个与 class 同名的函数来定义。

当且仅当要生成一个 class 的新的实例 (instance)的时候,也就是当且仅当声明一个新的对象,或给该 class 的一个对象分配内存的时候,

这个构造函数将自动被调用。下面,我们将实现包含一个构造函数的Rectangle class:

 

 

#include <iostream> using namespace std; class Rectangle { int width, height; public: Rectangle (int, int); int area () {return (width*height);} }; Rectangle::Rectangle (int a, int b) { width = a; height = b; } int main () { Rectangle rect (3,4); Rectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; }
rect area: 12 rectb area: 30

 

这个例子的输出结果与前面一个没有区别。在这个例子中,我们只是把函数 set_values 换成了class 的构造函数 constructor。注意这里参数是如何在 class 实例 (instance)生成的时候传递给构造函数的:

 

    Rectangle rect (3,4);

    Rectangle rectb (5,6);

 

同时你可以看到,构造函数的原型和实现中都没有返回值(return value),也没有 void 类型声明。构造函数必须这样写。一个构造函数永远没有返回值,也不用声明 void,就像我们在前面的例子中看到的



你可能感兴趣的:(Constructor)