您的位置:首页 > 编程语言 > C语言/C++

C++ class constructor and destructor

2015-11-25 14:40 417 查看
构造函数:

构造函数与class名字相同,没有返回类型;objects在生成的时候会自动生成执行;在给初始化的时候非常有用。

#include <iostream>
using namespace std;

class Box
{
public:
double getlength();
void setlength(double len);
Box ();

private:
double length;
};

Box::Box()
{
cout << "the object is created" << endl;
}

void Box::setlength(double len)
{
length=len;
}

double Box::getlength()
{
return length;
}

int main()
{
Box box1;
box1.setlength(11.1);
cout << box1.getlength();
return 0;
}


此处需注意,class定义完之后需要加上分号!

构造函数还可以用来赋值:

Box::Box(double len):length(len)
{
cout << "the object is created"<< endl;
}


Box::Box(double len)
{
cout << "the object is created" << endl;
length=len;
}

如果初始变量比较多的话,直接在第一行length(len)后面加逗号(,),width(wid)

main函数就可以这么写:

int main()
{
Box box1(11.1);
cout << box1.getlength();
return 0;
}
析构函数:

与构造函数同名,前面有一个前缀,~Box   没有返回类型和参数类型,只有一个这种形式 ~Box();

主要是为了释放空间,删除object时候用。比如main()函数结束的时候,执行到return 0;

Box::~Box()
{
cout << "the object is deleted"<< endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 基础学习