#include <iostream>
class CRectangle{
int x,y;
public:
CRectangle(void);
CRectangle(int ,int );
void set_values(int ,int );
int area(void);
};
CRectangle::CRectangle(void)
{
x=0;
y=0;
}
CRectangle::CRectangle(int a,int b)
{
x=a;
y=b;
}
void CRectangle::set_values(int a ,int b)
{
x=a;
y=b;
}
int CRectangle::area()
{
return (x*y);
}
int main(int argc,char *argv[])
{
CRectangle rect,rectb(2,3);
std::cout<<"area:"<<rect.area()<<std::endl;
std::cout<<"area:"<<rectb.area()<<std::endl;
rect.set_values(3,4);
std::cout<<"area:"<<rect.area()<<std::endl;
}
这是一个简单的例子。实现了构造函数的重载。
下面加上析构函数来看看:
#include <iostream>
class class_name{
int *width,*height;
public:
class_name(int ,int );
~class_name();
int area(void){return ((*width)*(*height));}
};
class_name::class_name(int a,int b ){
width=new int;
height=new int;
*width =a;
*height=b;
}
class_name::~class_name(){
delete width;
delete height;
}
int main(){
class_name rect(3,4);
std::cout<<"rect area: "<<rect.area()<<std::endl;
return 0;
}
你可以看到,构造函数的原型和实现中都没有返回值(return value),也没有void 类型声明。构造函数必须这样写。一个构造函数永远没有返回值,也不用声明void,就像我们在前面的例子中看到的。
析构函数Destructor 完成相反的功能。它在objects被从内存中释放的时候被自动调用。释放可能是因为它存在的范围已经结束了(例如,如果object被定义为一个函数内的本地(local)对象变量,而该函数结束了);或者是因为它是一个动态分配的对象,而被使用操作符delete释放了。
析构函数必须与class同名,加水波号tilde (~) 前缀,必须无返回值。
析构函数特别适用于当一个对象被动态分别内存空间,而在对象被销毁的时我们希望释放它所占用的空间的时候。