c++学习(第13天)深拷贝与浅拷贝(黑马程序员学习笔记)
2021-05-31 20:24
1221 查看
浅拷贝:简单的赋值拷贝操作
#include<iostream> using namespace std; //深拷贝与浅拷贝问题 class person { public: person() { cout << "构造函数" << endl; } person(int age1) { age2 = age1; cout << "有参函数" << endl; } ~person() { cout << "析构函数" << endl; } int age2; }; void test() { person p(18); cout << "p的年龄为:" << p.age2 << endl; person p1(p);//浅拷贝 cout << "p1的年龄为:" << p1.age2 << endl; } int main() { test(); system("pause"); return 0; }
深拷贝:在堆区重新申请空间,进行拷贝操作
注意:
学习深拷贝之前,一定要掌握new关键字使用,new 关键字使用
#include<iostream> using namespace std; //深拷贝与浅拷贝问题 class person { public: person() { cout << "构造函数" << endl; } person(int age1,int height) { age2 = age1; //利用new 关键字开辟的内存空间,返回的是内存空间的地址 height2 = new int(height); cout << "有参函数" << endl; } person(const person &p) { age2 = p.age2;//浅拷贝 //height2 = p.height2;浅拷贝 height2 = new int(*p.height2);//深拷贝 cout << "拷贝构造函数" << endl; } ~person() { //析构函数的作用:将堆区开辟的内存空间释放掉 if(height2 !=NULL) { delete height2; height2 = NULL; } cout << "析构函数" << endl; } int age2; //int 类型的指针 int* height2; }; void test() { person p(18,175); cout << "p的年龄为:" << p.age2 << endl; cout << "p的身高为:" << *p.height2 << endl; person p1(p); cout << "p1的年龄为:" << p1.age2 << endl; cout << "p1的身高为:" << *p1.height2 << endl; } int main() { test(); system("pause"); return 0; }
初始化列表
构造函数():属性1(值1),属性2(值2)... {}
#include<iostream> using namespace std; class person { public: //传统构造函数 /* person(int a,int b,int c) { age = a; height = b; weight = c; cout << "构造函数" << endl; } */ //初始化列表 person(int a, int b, int c) :age(a), height(b), weight(c) { } void printperson() { cout << "age:" << age << endl; cout << "height:" << height<< endl; cout << "weight:" << weight << endl; } private: int age; int height; int weight; }; int main() { person p(18,175,100); p.printperson(); system("pause"); return 0; }
静态成员
静态成员就是在成员变量和成员函数前加上关键字static,称为静态成员
静态成员函数 所有对象共享同一个函数 静态成员函数只能访问静态成员变量
#include<iostream> using namespace std; class person { public: //静态成员函数 static void func() { cout << "静态成员函数" << endl; } }; void test() { //调用静态成员函数 //1.通过对象访问 person p; //p.func(); //2.通过类名访问 person::func(); } int main() { test(); system("pause"); return 0; }
相关文章推荐
- c++学习笔记(三):深拷贝与浅拷贝及等号运算符重载
- GeekBand学习笔记:C++三大函数:拷贝构造、拷贝赋值、析构函数
- 黑马程序员_学习笔记第13天 String类
- C++学习笔记(字符串string、vector_deque、queue,multiset、map、multimap、容器拷贝问题)
- C++基础的不能再基础的学习笔记——拷贝控制示例(二)
- C++ Primer Plus学习笔记之拷贝构造函数
- 【C++学习笔记】拷贝构造函数以及深拷贝和浅拷贝
- C++学习笔记【第三部分第十三章:拷贝控制】
- C++学习笔记(字符串string、vector_deque、queue,multiset、map、multimap、容器拷贝问题)(复制粘贴,方便后面翻阅)
- c++学习笔记之拷贝
- c++学习笔记--拷贝控制的三/五法则
- Inside the C++ Object Model 学习笔记 第五章构造 解构 拷贝语意学
- C++ 学习笔记(13)拷贝构造函数、拷贝赋值运算符、移动构造函数、移动赋值运算符、析构函数、右值引用、引用限定符
- C++学习笔记-类5-浅拷贝和深拷贝以及赋值操作符的重载
- C++基础的不能再基础的学习笔记——拷贝控制(一)
- C++学习笔记之拷贝构造
- VS2010 C++ 学习笔记(五) 析构函数 深拷贝浅拷贝 小练习
- VS2010 C++ 学习笔记(四) 1.数据的封装 2.类外定义 3.构造函数(无参,有参,重载,初始化列表,拷贝) 4.练习
- 黑马程序员_学习笔记第13天——String类
- 黑马程序员学习笔记_OC之内存管理 2