定义
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。构造函数可用于为某些成员变量设置初始值。
简言之就是很成员函数一模一样但是没有返回类型名字和类的名字完全一样。在建立新的对象的时候自动创建
普通的构造函数
Line();//class 里面的声明
Line::Line(void){"xigouhanshu"}//真正的成员函数定义
#include <iostream>
using namespace std;
class Line
{
public:
Line(); // 这是构造函数
private:
double length;
};
// 成员函数构造函数
Line::Line(void)
{
cout << "Object is being created" << endl;
}
// 程序的主函数
int main( )
{
Line line;
return 0;
}
会输出Object is being created
带参数的构造函数
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // 这是构造函数
private:
double length;
};
// 成员函数定义,包括构造函数
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// 程序的主函数
int main( )
{
//一次构造
Line line(10.0);
// 获取默认设置的长度
cout << "Length of line : " << line.getLength() <<endl;
// 再次设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
用构造函数进行初始化
C::C( double a, double b, double c): X(a), Y(b), Z(c)
{
....
}