构造函数&析构函数
类的构造函数——创建类的对象test
类的析构函数——删除所创建类的对象test
类的构造函数——创建类的对象
类的构造函数是一个特殊的成员函数,它会在每次创建类的新对象时执行。
构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。
test
#include
using namespace std;
class Line
{
public:
Line(); // 这是构造函数
void setLength(double len);
double getLength();
private:
double length;
};
// Line类的构造函数
Line::Line()
{
cout return length;}
// 程序的主函数
int main( )
{
Line line;//类 对象 运行构造函数并输出
// 设置长度
line.setLength(6.0);
cout
public:
Line(); // 这是构造函数声明
~Line(); // 这是析构函数声明
void setLength( double len );
double getLength( );
private:
double length;
};
// 成员函数定义,包括构造函数和析构函数
Line::Line()
{
cout
length = len;
}
double Line::getLength(){
return length;
}
// 程序的主函数
int main( )
{
Line line;
// 设置长度
line.setLength(6.0);
cout |