构造函数初始化列表
来源:互联网 发布:如何关闭netstat 端口 编辑:程序博客网 时间:2024/05/23 01:59
-----------------siwuxie095
默认构造函数,即在实例化对象时不需要传递参数的构造函数
分为:无参默认构造函数和有参默认构造函数
如:
初始化列表
格式:在构造函数的后边用冒号隔开,对于多个数据成员,中间用逗号隔开,
赋值时要用括号,而不能用等号
如:
初始化列表特性:
(1)初始化列表先于构造函数执行,即编译器会先给初始化列表的
数据成员赋值,再执行构造函数当中的代码
(2)初始化列表只能用于构造函数,在其它函数的后边用初始化列表
将导致语法错误
(3)初始化列表可以同时初始化多个数据成员,并且效率高、速度快,
推荐使用初始化列表的方式来完成对数据成员的初始化操作
大家肯定会有疑问:C++大费周章地搞了一个初始化列表,而初始化列表
的工作又由构造函数完全可以代劳了,最多也就稍微慢点,那初始化列表
的意义何在?
初始化列表的必要性:
如:定义一个圆的类,需要定义一个圆周率Pi 的值,且用 const 修饰,
因为Pi 是不变的,此时,如果通过构造函数来初始化这个常量,编译器
就会报错,且会告诉我们,因为m_dPi 是const 修饰的常量,不能给
它再赋值,即m_dPi = 3.14 相当于第二次给它赋值
如果想给Pi 赋值并且又不导致语法错误,就必须通过初始化列表来完成
程序:
Teacher.h:
#include <string>
using namespace std;
class Teacher
{
public:
Teacher(string name ="Jim", int age = 1,int m = 100);//有参默认构造函数
void setName(string name);
string getName();
void setAge(int age);
int getAge();
int getMax();//能带学生的最大数量
private:
string m_strName;
int m_iAge;
const int m_iMax;//const修饰的数据成员在构造函数中只能用初始化列表初始化
};
Teacher.cpp:
#include"Teacher.h"
#include <iostream>
using namespace std;
//初始化列表先于构造函数执行
Teacher::Teacher(string name,int age, int m) :m_strName(name), m_iAge(age), m_iMax(m)
{
cout <<"Teacher(string name, int age)" << endl;
}
void Teacher::setName(string name)
{
m_strName = name;
}
string Teacher::getName()
{
return m_strName;
}
void Teacher::setAge(int age)
{
m_iAge = age;
}
int Teacher::getAge()
{
return m_iAge;
}
int Teacher::getMax()
{
return m_iMax;
}
main.cpp:
#include <stdlib.h>
#include"Teacher.h"
#include <iostream>
using namespace std;
int main(void)
{
Teacher t1;
cout << t1.getName() <<" " << t1.getAge() << " " << t1.getMax() << endl;
Teacher t2("Merry",12, 150);
cout << t2.getName() <<" " << t2.getAge() << " " << t2.getMax() << endl;
system("pause");
return0;
}
【made by siwuxie095】
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- 构造函数初始化列表
- yolo1,yolo2论文理论总结
- 文件的输入和输出
- Angular2 脏检查过程
- 【动态规划】#1037 : 数字三角形
- 浅谈Python Django框架
- 构造函数初始化列表
- 基于OpenGL ES 的深度学习框架编写
- Java IO学习要点导图
- FastStone Capture 注册码
- 各种HTTP状态汇总 (web服务器请求服务报错提示)
- Python requests爬虫爬取小说数据
- 图形解锁验证码破解(附Python代码)
- telnet配置和telnet用法
- 关于switch语句