6-4 C++构造函数初始化列表
上图:实例化过程中不需要传递参数的构造函数称为默认构造函数;
推荐使用初始化列表的方式进行初始化操作;
此时语法错误:const常量m_dPi第二次赋值了;
解决办法:初始化列表:
6-5 初始化列表编码
要求:
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关键字是把那个Max声明成常量,当初始化完了之后就不能再改变它的值了,初始化时可以改变;
};
Teacher.cpp:
#include"Teacher.h"
#include<iostream>
#include<string>
using namespace std;
Teacher::Teacher(string name,int age,int m):m_strName(name),m_iage(age),m_iMax(m)//初始化列表;默认参数.h写了 这里就不用写了
{
cout<<"初始化列表构造函数"<<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;
}
demo.cpp:
#include<iostream>
#include<stdlib.h>
#include<string>
#include "Teacher.h"
using namespace std;
int main()
{
Teacher a;//不用加空括号,否则会报错
cout<<a.getName()<<" "<<a.getAge()<<" "<<a.getMax()<<endl;
Teacher b("fantic",21,150);
cout<<b.getName()<<" "<<b.getAge()<<" "<<b.getMax()<<endl;
system("pause");
return 0;
}
输出结果:
初始化列表构造函数
jim 1 100
初始化列表构造函数
fantic 21 150
请按任意键继续. . .
6-6 练习
A.当构造函数没有参数时也叫做默认构造函数。√
B.一个类至少有一个默认构造函数。×(可以强制构造函数有参数,无默认值)
C.当构造函数有参数,但每个参数都有默认值时,也称为默认构造函数。√
D.当实例化对象时,如果不使用任何参数,则调用的是默认构造函数。√
补充:
默认构造函数:就是在没有显式提供初始化式时调用的构造函数。
它由不带参数的构造函数,或者为所有的形参提供默认实参的构造函数定义。
如果定义某个类的变量时没有提供初始化时就会使用默认构造函数。