您的位置:首页 > 编程语言 > C语言/C++

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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐