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 家长会简短祝福语