C ++默认构造函数
类构造函数是类的特殊成员函数,只要我们创建该类的新对象,该构造函数便会执行。
构造函数将具有与类完全相同的名称,并且根本没有任何返回类型,甚至没有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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短