构造函数
来源:互联网 发布:socket java面试题 编辑:程序博客网 时间:2024/06/03 23:43
类的构造函数
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。
构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。构造函数可用于为某些成员变量设置初始值。
#include <iostream>using namespace std;class Line{ public: void setLength( double len ); double getLength( void ); Line(); // 这是构造函数 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 createdLength of line : 6
带参数的构造函数
默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值,如下面的例子所示:
#include <iostream>using namespace std;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;}
输出:
Object is being created, length = 10Length of line : 10Length of line : 6
使用初始化列表来初始化字段
Line::Line( double len): length(len){ cout << "Object is being created, length = " << len << endl;}
上面的语法等同于如下语法:
Line::Line( double len){ cout << "Object is being created, length = " << len << endl; length = len;}
假设有一个类 C,具有多个字段 X、Y、Z 等需要进行初始化,同理地,您可以使用上面的语法,只需要在不同的字段使用逗号进行分隔,如下所示:
C::C( double a, double b, double c): X(a), Y(b), Z(c){ ....}
0 0
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 构造函数
- 嵌入式Linux文件系统详细介绍
- 51nod 1058 N的阶乘的长度
- 无题
- Error in swirlExpectation(condition(object))
- Qt——仿bilibili直播的调音量控件
- 构造函数
- 西部世界
- redis源码分析 -- 内存管理
- 操作系统实验(1):定时中断处理
- leetcode:Find All Anagrams in a String 滑动窗口方法总结
- 【css】路径data:image/png;base64的用法详解
- Java线程同步实例
- Intel 8086 汇编指令手册
- GDI+环境初始化