C++ 深拷贝与浅拷贝
生活随笔
收集整理的這篇文章主要介紹了
C++ 深拷贝与浅拷贝
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include<iostream>
using namespace std;
#include<string>class Person {public:Person() {cout << "Person的無參構造函數調用" << endl;};Person(int age) {m_Age = age;cout << "Person的有參構造函數調用" << endl;};//拷貝構造函數Person(const Person &p) {cout << "Person的拷貝構造函數調用" << endl;//將傳入的人身上的所有屬性,拷貝到我身上m_Age = p.m_Age;// m_Age = p.m_Age;};~Person() {cout << "Person的析構函數調用" << endl;}int m_Age;};void test() {//1.括號法Person p1; //默認構造函數調用Person p2(10); //有參構造函數Person p3(p2); //拷貝構造函數//2、顯示法//3、隱式轉換法}//1、使用一個已經創建完畢的對象來初始化- -個新對象
void test01() {Person p1(18);cout << "p1的年齡為:" << p1.m_Age << endl;Person p2(p1);cout << "p2的年齡為:"<< p2.m_Age << endl;};//2、值傳遞的方式給函數參數傳值
void doWork(Person p) {
}
void test02() {Person p;doWork(p);
}int main() {test01();// test01();system("pause");}
?
?
?
深拷貝解決淺拷貝的堆內存重復釋放問題
//自己實現拷貝構造函數解決淺拷貝帶來的問題Person(const Person &p) { //拷貝構造函數編譯器默認實現cout << "Person 拷貝構造函數調用" << endl;m_Age = p.m_Age;// m_Height = p.m_Height; //拷貝構造函數編譯器默認實現//深拷貝操作 解決淺拷貝堆內存重復釋放m_Height = new int(*p.m_Height);}?
#include<iostream> using namespace std; #include<string>class Person {public:Person() {cout << "Person的無參構造函數調用" << endl;};Person(int age, int height) {m_Age = age;cout << "Person的有參構造函數調用" << endl;m_Height = new int(height);};/*Person(const Person &p){ //拷貝構造函數編譯器默認實現cout << "Person 拷貝構造函數調用"<< endl;m_Age = p.m_Age;m_Height = p.m_Height; //}*///自己實現拷貝構造函數解決淺拷貝帶來的問題Person(const Person &p) { //拷貝構造函數編譯器默認實現cout << "Person 拷貝構造函數調用" << endl;m_Age = p.m_Age;// m_Height = p.m_Height; //拷貝構造函數編譯器默認實現//深拷貝操作 解決淺拷貝堆內存重復釋放m_Height = new int(*p.m_Height);}//拷貝構造函數編譯器默認實現/*Person(const Person &p) {cout << "Person的拷貝構造函數調用" << endl;//將傳入的人身上的所有屬性,拷貝到我身上m_Age = p.m_Age;// m_Age = p.m_Age;}; */~Person() {if (m_Height != NULL) {delete m_Height;m_Height = NULL;}cout << "Person的析構函數調用" << endl;}int m_Age;int *m_Height; //身高 };//1、使用一個已經創建完畢的對象來初始化- -個新對象 void test01() {Person p1(18,160);cout << "p1的年齡為:" << p1.m_Age << "身高為:"<< *p1. m_Height << endl;Person p2(p1);cout << "p2的年齡為:" << p2.m_Age << "身高為:" << *p2.m_Height << endl;};//2、值傳遞的方式給函數參數傳值 void doWork(Person p) { } void test02() {Person p;doWork(p); }int main() {test01();// test01();system("pause");}?
總結:如果屬性有在堆區開辟的,一定要自己提供拷貝構造函數,防止淺拷貝帶來的問題
總結
以上是生活随笔為你收集整理的C++ 深拷贝与浅拷贝的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Bit-Z如何注册?【新手操作指南】
- 下一篇: C++ 友元函数