构造函数和析构函数是类的特殊成员,它们分别在对象创建和撤销时被自动调用。

构造函数是类中特殊的成员函数,目的和任务是用于初始化对象的数据成员。

class类名
{
public:
构造函数名称(参数表)
{
函数体
}
private:
数据成员;
};

例如:定义一个包含构造函数的汽车类Car

  1. class Car //定义类
  2. {
  3. public:
  4. Car() //构造函数
  5. {
  6. m_strCarname = “default name”;
  7. }
  8. private:
  9. string m_strCarname; //数据成员
  10. };

构造函数的规则:

构造函数名与类名相同

构造函数名前没有返回值类型声明

构造函数中不能通过return语句返回一个值

通常构造函数的访问修饰符为public

构造函数定义形式:
类名::构造函数()
{
}

类中定义构造函数后,编译器不再提供默认构造函数
只要类中定义了一个构造函数,C++将不再提供默认的构造函数。如果在类中定义的是带参数的构造函数,创建对象时想使用不带参数的构造函数,则需要再实现一个无参的构造函数,否则编译出错,类中的构造函数和调用方式必须一致,如下代码所示:

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Car{
  5. public:
  6. Car(string con_carname){ //定义带参数的构造函数
  7. m_strCarName=con_carname;
  8. }
  9. void show();
  10. private:
  11. string m_strCarName;
  12. };
  13. void Car::show(){
  14. cout<<(*this).m_strCarName<<endl;
  15. }
  16. int main(){
  17. Car mycar; //错误,类Car不存在默认构造函数
  18. //正确的方式
  19. 1.Car mycar("jeta");
  20. 2.Car mycar=Car("jeta");
  21. 3.Car *ptrmycar=new Car("jeta");
  22. (*ptrmycar).show();
  23. mycar.show();
  24. return 0;
  25. }

1. 系统提供的默认隐式构造函数

  1. #include<iostream>
  2. using namespace std;
  3. class Car{
  4. public:
  5. void disp_mems_value();
  6. private:
  7. int m_nWheels;
  8. int m_nSeats;
  9. int m_nLength;
  10. };
  11. void Car::disp_mems_value(){
  12. cout<<"wheels="<<m_nWheels<<endl;
  13. cout<<"seats="<<m_nSeats<<endl;
  14. cout<<"length="<<m_nLength<<endl;
  15. }
  16. int main(){
  17. Car mycar;//默认构造函数
  18. mycar.disp_mems_value();
  19. return 0;
  20. }
  21. //从运行结果看,系统提供的默认无参构造函数并没有为成员提供有效初值

2. 自定义无参构造函数

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Car{ //定义类
  5. public:Car(){ //定义构造函数
  6. cout<<"Car constructor!"<<endl;
  7. m_strCarName="default name";
  8. }
  9. string get_carname(){
  10. return m_strCarName;
  11. }
  12. private:
  13. string m_strCarName;
  14. };
  15. int main(){
  16. Car mycar;//调用默认构造函数
  17. cout<<"car name:"<<mycar.get_carname()<<endl;
  18. return 0;
  19. }

3. 自定义带参数的构造函数

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Car{
  5. public:
  6. Car(string con_carname,int con_seats){ //定义带有两个参数的构造函数
  7. cout<<"Calling Car constructor,set carname,seats!"<<endl;
  8. m_strCarName=con_carname;
  9. m_nSeats=con_seats;
  10. }
  11. Car(string con_carname){
  12. cout<<"Calling Car constructor,set carname!"<<endl;
  13. m_strCarName=con_carname;
  14. }
  15. void disp_memsg(){
  16. cout<<"Carname:"<<m_strCarName<<","<<"seats="<<m_nSeats<<endl;
  17. }
  18. private:
  19. string m_strCarName;
  20. int m_nSeats;
  21. };
  22. int main(){
  23. //对象声明的初始化的几种不同的方法
  24. Car mycar=Car("my new car",4);
  25. Car tomcar("tom's car");
  26. Car *pretommycar=new Car("tommy's car");
  27. mycar.disp_memsg();
  28. tomcar.disp_memsg();
  29. (*pretommycar).disp_memsg();
  30. }

构造函数的初始化

1、对于带默认参数值的构造函数来说,需要防止调用的二义性。
2、构造函数中若第n个参数有默认值,则其后的所有参数都应该有默认值,若构造函数定义为如下内容,则编译出错:
Car(string con_carname = “my car name”, int con_seats);
上述代码中,第一个参数有默认值,则后续所有参数均应该有默认值。

1.通过初始化列表来实现数据成员的初始化

语法格式

类名::构造函数名(参数列表):数据成员1(参数1),数据成员的2(参数2),…,数据成员n(参数n)
{
构造函数体
}
构造函数若在类外定义需要在构造函数名程前添加类名和::

  1. #include <iostream>
  2. using namespace std;
  3. class Student{
  4. private:
  5. string m_name;
  6. int m_age;
  7. float m_score;
  8. public:
  9. Student(string name, int age, float score);
  10. void show();
  11. };
  12. //采用初始化列表
  13. Student::Student(string name, int age, float score): m_name(name), m_age(age), m_score(score){
  14. //TODO:
  15. }
  16. void Student::show(){
  17. cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
  18. }
  19. int main(){
  20. Student stu("小明", 15, 92.5f);
  21. stu.show();
  22. Student *pstu = new Student("李华", 16, 96);
  23. pstu -> show();
  24. return 0;
  25. }

2.默认参数值的构造函数

语法格式

类名::构造函数名(类型 参数1 = 默认值, 类型 参数2 = 默认值)
{
函数体
}

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Box
  5. {
  6. public:
  7. Box(int h = 10, int w = 10, int len = 10);
  8. int volume();
  9. private:
  10. int height;
  11. int width;
  12. int length;
  13. };
  14. Box::Box(int h,int w,int len)
  15. {
  16. height = h;
  17. width = w;
  18. length = len;
  19. }
  20. int Box::volume()
  21. {
  22. return (height*width*length);
  23. }
  24. int main()
  25. {
  26. Box box1;
  27. cout << "The volumme of box1 is:" << box1.volume() << endl;
  28. Box box2(15);
  29. cout << "The volumme of box2 is:" << box2.volume() << endl;
  30. Box box3(15, 30);
  31. cout << "The volumme of box3 is:" << box3.volume() << endl;
  32. Box box4(15,30,20);
  33. cout << "The volumme of box4 is:" << box4.volume() << endl;
  34. return 0;
  35. }

以上代码在调用过程中首先调用了无参的构造函数,系统调用默认构造函数,各个形参的取值均取默认值10,
在定义对象只有一个的时候,只给第一个赋值为给定值,未指定的还是默认值10,同理,程序都皆如此。
可以看到:在构造函数中使用默认参数是方便而有效的,它提供了建立对象时的多种选择,它的作用相当于好几个重载的构造函数。它的好处是:即使在调用构造函数的时候,没有提供实参值,不仅不会出错,而且还确保按照默认的参数值对对象进行初始化,尤其在希望对每一个对象都有同样的初始化的状况的时候用这种方法更为方便。不需输入数据,对象会按事先指定的值进行初始化。

  1. #include<iostream>
  2. using namespace std;
  3. class Circle{
  4. public:
  5. Circle(int a=1,int b=2,int c=3){//本构造函数是带默认值的默认构造函数
  6. x=a;
  7. y=b;
  8. z=c;
  9. }
  10. void show();
  11. private:
  12. int x;
  13. int y;
  14. int z;
  15. };
  16. void Circle::show(){
  17. cout<<"x="<<(*this).x<<" y="<<(*this).y<<" z="<<(*this).z<<endl;
  18. }
  19. int main(){
  20. Circle c1
  21. c1.show();
  22. Circle c2(5);
  23. c2.show();
  24. Circle c3(5,6);
  25. c3.show();
  26. Circle c4(5,6,7);
  27. c4.show();
  28. return 0;
  29. }

成员变量的初始化顺序与初始化列表中列出的变量的顺序无关,它只与成员变量在类中声明的顺序有关

  1. #include<iostream>
  2. using namespace std;
  3. class Demo{
  4. private:
  5. int m_a;
  6. int m_b;
  7. public:
  8. Demo(int b);
  9. void show();
  10. };
  11. Demo::Demo(int b):m_b(b),m_a(m_b){
  12. }
  13. void Demo::show(){
  14. cout<<m_a<<","<<m_b<<endl;
  15. }
  16. int main(){
  17. Demo obj(100);
  18. obj.show();
  19. return 0;
  20. }

在初始化列表中,我们将 m_b 放在了 m_a 的前面,看起来是先给 m_b 赋值,再给 m_a 赋值,这是错误的!成员变量的赋值顺序由它们在类中的声明顺序决定,在 Demo 类中,我们先声明的 m_a,再声明的 m_b,所以构造函数和下面的代码等价:

  1. Demo::Demo(int b): m_b(b), m_a(m_b){
  2. m_a = m_b;
  3. m_b = b;
  4. }

给 m_a 赋值时,m_b 还未被初始化,它的值是不确定的,所以输出的 m_a 的值是一个奇怪的数字;给 m_a 赋值完成后才给 m_b 赋值,此时 m_b 的值才是 100。
obj 在栈上分配内存,成员变量的初始值是不确定的。

const 成员变量的初始化

初始化 const 成员变量的唯一方法就是使用初始化列表的方式赋值

  1. #include<iostream>
  2. using namespace std;
  3. class VLA{
  4. private:
  5. const int m_len;
  6. int *m_arr;
  7. public:
  8. VLA(int len);
  9. void show(int len);
  10. };
  11. //必须使用初始化列表来初始化 m_len
  12. VLA::VLA(int len):m_len(len){
  13. m_arr=new int[len];
  14. }
  15. void VLA::show(int len){
  16. for(int i=0;i<len;i++)
  17. cout<<"m_arr["<<i<<"]="<<m_arr[i]<<" "<<endl;
  18. }
  19. int main(){
  20. VLA a=VLA(10);
  21. a.show(10);
  22. return 0;
  23. }

包含对象成员的类的构造函数

C++中允许将一个已定义的类对象作为另一个类的数据成员,即类中的数据成员可以是其他类的对象,称这种成员是类的子对象或成员对象。
定义这种类的格式

  1. class 新类名
  2. {
  3. 类名1 成员1;
  4. 类名2 成员2;
  5. …
  6. };

若类X中有成员对象,则创建X类对象时
1.先执行成员对象的构造函数
2.初始化成员函数对象
3.执行类X的构造函数,初始化其他非对象成员
同时,若类X的成员对象的构造函数带有参数,则定义X类的构造函数时,应使用初始化列表的形式对成员对象初始化
具体格式如下:

  1. class X
  2. {
  3. public:
  4. X(参数表);
  5. private:
  6. 类型1 成员1;
  7. 类型2 成员2;
  8. …
  9. };
  10. //X构造函数,使用初始化列表对成员对象初始化
  11. X::X(参数表):成员1(参数表1),成员2(参数表2),...
  12. {
  13. 构造函数体
  14. }
  1. #include<iostream>
  2. #include<cstring>
  3. using namespace std;
  4. class Date{
  5. public:
  6. Date(int y,int m,int d);
  7. void show();
  8. private:
  9. int m_nYear,m_nMonth,m_nDay;
  10. };
  11. Date::Date(int y,int m,int d){
  12. cout<<"Date constructor!"<<endl;
  13. m_nYear=y;
  14. m_nMonth=m;
  15. m_nDay=d;
  16. }
  17. void Date::show(){
  18. cout<<m_nYear<<"_"<<m_nMonth<<"_"<<m_nDay<<endl;
  19. }
  20. class Student{
  21. public:
  22. Student(string con_name,int con_id,int y,int m,int d);
  23. void disp_msg();
  24. private:
  25. Date m_iBirthday; //Date类型的数据成员
  26. string m_gName;
  27. int m_nID;
  28. };
  29. Student::Student(string con_name,int con_id,int y,int m,int d):m_iBirthday(y,m,d){
  30. cout<<"Student constructor!"<<endl;
  31. m_gName=con_name;
  32. m_nID=con_id;
  33. }
  34. void Student::disp_msg(){
  35. cout<<"std name:"<<m_gName<<",id="<<m_nID<<",birthday:";
  36. m_iBirthday.show();
  37. }
  38. int main(){
  39. Student student("xiaoming",1,1998,10,25);
  40. student.disp_msg();
  41. return 0;
  42. }

上述代码同样可以用定义Date类的拷贝构造函数的方式来实现

  1. Student::Student(string con_name,int con_id,Date &con_birthday):m_iBirthday(con_birthday){
  2. cout<<"Student constructor!"<<endl;
  3. m_gName=con_name;
  4. m_nID=con_id;
  5. }
  6. int main(){
  7. Date date(1998,10,25);
  8. Student student("xiaoming",1,date);
  9. student.disp_msg();
  10. return 0;
  11. }