C++ 的构造函数的作用:初始化类对象的数据成员。
构造函数
类的对象被创建的时候,编译系统对该对象分配内存空间,并自动调用构造函数,完成类成员的初始化,C++的构造函数可以有多个,创建对象时编译器会根据传入的参数不同调用不同的构造函数。
构造函数的特定:以类名作为函数名,无赶回类型。
常见的构造函数有三种写法:
无参构造函数,一般构造函数,复制构造函数。
1:无参构造函数
如果创建一个类,没有写任何构造函数,则系统会自动生成默认的无参构造函数,且此函数为空。
默认构造函数(default constructor)就是在没有显式提供初始化时调用的构造函数,如果定义某个类的变量,但是没有提供初始化时就会默认使用构造函数,但是只要有一种构造函数系统就不会再自动生成这样一个默认的构造函数。
#include <iostream>
using namespace std;
class Student {
public:
int m_age;
int m_score;
// 1. 无参构造函数
Student() {
m_age = 18;
m_score = 99;
cout << "自动调用无参构造函数" << endl;
}
};
int main()
{
Student student1;
return 0;
}
// 打印输出
自动调用无参构造函数
2:一般构造函数
一般构造函数有两种写法
2.1.1 方式一:构造函数:初始化类对象的数据成员
初始化列表方式:以一个冒号开始,接着是以逗号分隔的数据成员列表,每个数据成员后面跟一个放在括号中的初始化值。
C++规定,对象的成员变量的初始化动作发生在进入构造函数本体之前,也就是说采用初始化列表的话,构造函数本体实际上不需要有任何操作,因此效率是极高的。
#include <iostream>
using namespace std;
class Student {
public:
int m_age;
int m_score;
// 1. 一般构造函数,初始化列表方式
Student(int age, int score) : m_age(age), m_score(score) {
cout << "2.1 初始化列表方式" << endl;
cout << "m_age = " << m_age<<endl;
cout << "m_score = " << m_score << endl;
}
};
int main()
{
Student student1(18,100);
return 0;
}
// 打印内容
2.1 初始化列表方式
m_age = 18
m_score = 100
2.1.2 :方式二:内部赋值
一般构造函数有多种参数形式,即一个类可以有多个一般构造函数,前提是参数的个数或者类型不同(C++的幻术重载机制)
#include <iostream>
using namespace std;
class Student {
public:
int m_age;
int m_score;
// 2. 一般构造函数
Student(int age, int score) {
m_age = age;
m_score = score;
cout << "2.2 内部赋值方式(1)" << endl;
cout << m_age << "," << m_score << endl;
}
Student(int age) {
m_age = age;
cout << "2.2 内部赋值方式(2)" << endl;
cout << m_age << endl;
}
};
int main()
{
Student student1(25, 100);
Student student2(30);
return 0;
}
// 打印
2.2 内部赋值方式(1)
25,100
2.2 内部赋值方式(2)
30
3:复制构造函数
复制构造函数,也称为拷贝构造函数
复制构造函数参数为类对象本身的引用,根据一个已存在的对象复制出一个新的对象,一般在函数中会将已存在对象的数据成员的值复制到一份新创建的对象中。
#include <iostream>
using namespace std;
class Student {
public:
int m_age;
int m_score;
// 2. 一般构造函数
Student(int age, int score) {
m_age = age;
m_score = score;
cout << "2.2 内部赋值方式(1)" << endl;
cout << m_age << "," << m_score << endl;
}
// 3. 复制构造函数
Student(Student& s) {
m_age = s.m_age;
m_score = s.m_score;
cout << "3. 复制构造函数" << endl;
cout << m_age << "," << m_score << endl;
}
};
int main()
{
Student student1(25, 100);
Student student2(student1);
return 0;
}
// 打印
2.2 内部赋值方式(1)
25,100
3. 复制构造函数
25,100