class Base{ public: Base(): m_a(0), m_b(0){ } Base(int a, int b): m_a(a), m_b(b){ } private: int m_a; int m_b; }; int main(){ int a = 10; int b = a; //拷贝 Base obj1(10, 20); Base obj2 = obj1; //拷贝 return 0; }b 和 obj2 都是以拷贝的方式初始化的,具体来说,就是将 a 和 obj1 所在内存中的数据按照二进制位(Bit)复制到 b 和 obj2 所在的内存,这种默认的拷贝行为就是浅拷贝,这和调用 memcpy() 函数的效果非常类似。
#include <iostream> #include <cstdlib> using namespace std; //变长数组类 class Array{ public: Array(int len); Array(const Array &arr); //拷贝构造函数 ~Array(); public: int operator[](int i) const { return m_p[i]; } //获取元素(读取) int &operator[](int i){ return m_p[i]; } //获取元素(写入) int length() const { return m_len; } private: int m_len; int *m_p; }; Array::Array(int len): m_len(len){ m_p = (int*)calloc( len, sizeof(int) ); } Array::Array(const Array &arr){ //拷贝构造函数 this->m_len = arr.m_len; this->m_p = (int*)calloc( this->m_len, sizeof(int) ); memcpy( this->m_p, arr.m_p, m_len * sizeof(int) ); } Array::~Array(){ free(m_p); } //打印数组元素 void printArray(const Array &arr){ int len = arr.length(); for(int i=0; i<len; i++){ if(i == len-1){ cout<<arr[i]<<endl; }else{ cout<<arr[i]<<", "; } } } int main(){ Array arr1(10); for(int i=0; i<10; i++){ arr1[i] = i; } Array arr2 = arr1; arr2[5] = 100; arr2[3] = 29; printArray(arr1); printArray(arr2); return 0; }运行结果:
0, 1, 2, 29, 4, 100, 6, 7, 8, 9
0, 1, 2, 29, 4, 100, 6, 7, 8, 9
#include <iostream> #include <ctime> #include <windows.h> //在Linux和Mac下要换成 unistd.h 头文件 using namespace std; class Base{ public: Base(int a = 0, int b = 0); Base(const Base &obj); //拷贝构造函数 public: int getCount() const { return m_count; } time_t getTime() const { return m_time; } private: int m_a; int m_b; time_t m_time; //对象创建时间 static int m_count; //创建过的对象的数目 }; int Base::m_count = 0; Base::Base(int a, int b): m_a(a), m_b(b){ m_count++; m_time = time((time_t*)NULL); } Base::Base(const Base &obj){ //拷贝构造函数 this->m_a = obj.m_a; this->m_b = obj.m_b; this->m_count++; this->m_time = time((time_t*)NULL); } int main(){ Base obj1(10, 20); cout<<"obj1: count = "<<obj1.getCount()<<", time = "<<obj1.getTime()<<endl; Sleep(3000); //在Linux和Mac下要写作 sleep(3); Base obj2 = obj1; cout<<"obj2: count = "<<obj2.getCount()<<", time = "<<obj2.getTime()<<endl; return 0; }运行结果:
本文链接:http://task.lmcjl.com/news/5589.html