复制构造函数与禁止复制即函数值传递的原理
什么是复制构造函数?一般都是系统有默认的复制构造函数,将类中的各个成员依次复制,我们基本不会手动使用它,如当对象产生副本时系统是通过复制构造函数来实现的。对于一般的程序开发来说它有什么用呢?我们可以通过自定义复制构造函数来按照我们自己的方式进行类的复制,也可以禁止复制……
#ifndef STUDENT_H #define STUDENT_H #include <iostream> using namespace std; class student { public: student(); student(int num, string name);//重载构造函数 student(student& st);//复制构造函数,形式是唯一的,必须用引用方式。 void CopyStudent(student st);//用于测试复制构造函数的效果 void print(); virtual ~student(); protected: private: int number; string name; }; #endif // STUDENT_H
#include "../include/student.h" student::student() { //ctor number = 0; this->name = "0000"; } student::student(int num, string name) { //ctor number = num; this->name = name; } student::student(student& st) { name = "copy"; //自定义的复制方式,复制给副本 } void student::print() { cout<<"number:" << number<<endl; cout<<"name:" << name<<endl; cout<<endl; } void student::CopyStudent(student st) { number = st.number; this->name = st.name; } student::~student() { //dtor }
#include <iostream> #include "include/student.h" using namespace std; int main() { student st0; student st1(1,"lee"); st0.print(); st1.print(); cout<< "after copy" <<endl; st0.CopyStudent(st1); st0.print(); return 0; }
如果整个程序中没有自定义复制构造函数,那么void CopyStudent(student st);函数就会将一个对象的成员拷贝到另一个对象中,这个过程是通过副本st传递的。但通过定义复制构造函数后,st副本无法按默认方式拷贝,而是使用自定义的复制构造函数方式传递。这样就可以实现禁止复制的效果。
本文是我学习了复制构造函数后写的,但对它在开发中怎么灵活使用还是一无所知,望同志们多多指教,有事例最好。另外通过学习我对函数中值的传递有了更为深刻的理解。