Deep copy ,Shallow copy, copy constructor,"="
Dog.h
#pragma once class Dog { public: char *name; Dog(); Dog(const Dog &it); ~Dog(); void operator =(const Dog &it); };
Dog.cpp
#include "Dog.h" #include<string.h> #include<iostream> using namespace std; //Constructor Dog::Dog() { name = new char[20]; memset(name,0,sizeof(name)); strcpy(name,"xiaohuang"); cout << "dog" << endl; } //Destructor Dog::~Dog() { delete []name; cout << "~dog" << endl; } // copy constructor Dog::Dog(const Dog &it) { name = new char[20]; memset(name, 0, sizeof(name)); strcpy(name, it.name); cout << "copy dog" << endl; } // overload = void Dog:: operator =(const Dog &it) { strcpy(name, it.name); cout << " = " << endl; }
main.cpp
#include"Dog.h"" using namespace std; void test(){ Dog d1; Dog d2 = d1; Dog d3; d3 = d1; } void main(){ test(); system("pause"); }
时间: 2024-10-08 05:49:03