拷贝构造函数是一种特殊的构造函数,具有单个形参,此形参是对该类型的引用。
(1)一个对象以值传递的方式传入函数体
(2)一个对象以值传递的方式从函数返回
(3)一个对象需要通过另外一个对象进行初始化。
如果一个类没有定义拷贝构造函数,编译器会默认提供拷贝构造函数。
main.cpp
#include <iostream> #include "student.h" #include <cstring> #include <stdio.h> using namespace::std; void foo(Student stu) { cout << "In fun " << __func__ << endl; printf("&stu = %x\n", &stu); // 调用析构函数(对应28行) } Student bar() { Student tom("tom", 112); // 定义类对象,调用构造函数 return tom; } int main() { cout << "Enter main---->\n"; Student joe("Joe", 111); // 定义类对象,调用构造函数 Student john = joe; // 1. 用一个对象构造另一个对象时,调用拷贝构造函数 cout << "\nCalling foo" << endl; printf("&joe = %x\n", &joe); foo(joe); // 2. 一个对象以值传递的方式传入函数体,也会调用拷贝构造函数 cout << "After call of foo\n" << endl; Student tom = bar(); // 一个对象以值传递的方式从函数体返回,调用构造函数??? printf("--------\n"); // 调用析构函数(对应16行、24行、23行) return 0; }
student.h
#ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED class Student{ public: Student(const char *pName = "NA", int ssId = 0); // 构造函数声明并初始化 ~Student(); // 析构函数 Student(const Student& s); // 拷贝构造函数 void print(); private: char name[40]; int id; }; #endif // STUDENT_H_INCLUDED
student.cpp
#include <iostream> #include "student.h" #include <cstring> #include <stdio.h> using namespace::std; Student::Student(const char *pName, int sId) // 构造函数的定义 :id(sId) // 冒号表示后面要对类的数据成员进行初始化 { memset(name, 0, 40); if(pName != NULL){ int len = strlen(pName); len = (len > 39) ? 39 : len; strncpy(name, pName, len); } cout << "constructor of student:" << name << endl; } Student::~Student() { cout << "destructor of student:" << name << endl; } void Student::print() { cout << "Student:" << name << endl; } Student::Student(const Student &s) { cout << "Constructing copy !" << endl; printf("&s = %x\n", &s); strcpy(name, "copy"); strcat(name, s.name); id = s.id; }