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;
};
// Member functions definitions including constructor
Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}输出
Object is being created Length of line : 6
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP