类构造函数是类的特殊成员函数,只要我们创建该类的新对象,该构造函数便会执行。
构造函数将具有与类完全相同的名称,并且根本没有任何返回类型,甚至没有void。构造函数对于为某些成员变量设置初始值非常有用。
以下示例解释了构造函数的概念-
#include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(); // This is the constructor private: double length; }; //成员函数定义,包括构造函数 Line::Line(void) { cout << "Object is being created" << endl; } void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } //程序的主要功能 int main() { Line line; //设置线长 line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; return 0; }
输出结果
Object is being created Length of line : 6