1.正常情况下的赋值操作:
int a = 10;
int b = a;
cout << a << endl;//10
cout << b << endl;//10
cout << &a << endl;//0x7ffed168b320
cout << &b << endl;//0x7ffed168b324
a = 20;
cout << a << endl;//20
cout << b << endl;//10
cout << &a << endl;//0x7ffed168b320
cout << &b << endl;//0x7ffed168b324
b = 30;
cout << a << endl;//20
cout << b << endl;//30
cout << &a << endl;//0x7ffed168b320
cout << &b << endl;//0x7ffed168b324
各自独立,开辟了一块新的地址来存放b。
赋值操作和传参是有区别,函数传参值传递不会对原值产生任何影响,传引用会修饰原值。
2.引用相当于指针常量,可以修改变量的值,但是不能修改指针的指向,也就是说初始化后不可以再修改指向其他变量。
int a = 10;
int &b = a;
cout << a << endl;//10
cout << b << endl;//10
cout << &a << endl;//0x7ffcb8b4f09c
cout << &b << endl;//0x7ffcb8b4f09c
a = 20;
cout << a << endl;//20
cout << b << endl;//20
cout << &a << endl;//0x7ffcb8b4f09c
cout << &b << endl;//0x7ffcb8b4f09c
b = 30;
cout << a << endl;//30
cout << b << endl;//30
cout << &a << endl;//0x7ffcb8b4f09c
cout << &b << endl;//0x7ffcb8b4f09c
3.深浅拷贝:
如果我们没有主动声明拷贝构造函数,但是main中仍然进行拷贝构造的时候,编译器会自动进行值拷贝,也就是浅拷贝。
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age,int height)
{
cout << "有参构造" << endl;
m_age = age;
m_height = new int(height);
public:
int m_age;
int *m_height;
};
int main()
{
Person p1(10, 170);
Person p2 = p1;//默认提供拷贝构造
cout << p1.m_age << " " << *p1.m_height << endl;
cout << p2.m_age << " " << *p2.m_height << endl;
}
有参构造
10 170
10 170
这样似乎没有什么问题,但是不符合规范,new在堆区开辟出来的数据需要手动开辟,手动删除,所以还要加入析构函数。
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age,int height)
{
cout << "有参构造" << endl;
m_age = age;
m_height = new int(height);
}
~Person()
{
cout << "析构函数" << endl;
if(m_height!=NULL)
{
delete m_height;
m_height = NULL;
}
}
public:
int m_age;
int *m_height;
};
int main()
{
Person p1(10, 170);
Person p2 = p1;//默认提供拷贝构造
cout << p1.m_age << " " << *p1.m_height << endl;
cout << p2.m_age << " " << *p2.m_height << endl;
}
编译以后报错,因为浅拷贝的原因,只是将值进行了值拷贝,在堆区上开辟的数据简单的分给了p1和p2, 析构的顺序是先p2后p1,p2析构的时候将堆区析构掉了,并且将指针置空,但是p1的m_height指针并不是空,所以还要进行析构一次,但是堆区上这个数据已经被析构掉了,所以出现内存泄漏。
解决问题:采用深拷贝,深拷贝的意思就是手动定义拷贝构造函数,将拷贝构造也重新new开辟新的堆区空间,各自对象对应不同的堆区空间。
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age,int height)
{
cout << "有参构造" << endl;
m_age = age;
m_height = new int(height);
}
Person(const Person &p)
{
cout << "拷贝构造" << endl;
m_age = p.m_age;
m_height = new int(*p.m_height);
}
~Person()
{
cout << "析构函数" << endl;
if(m_height!=NULL)
{
delete m_height;
m_height = NULL;
}
}
public:
int m_age;
int *m_height;
};
int main()
{
Person p1(10, 170);
Person p2 = p1;//默认提供拷贝构造
cout << p1.m_age << " " << *p1.m_height << endl;
cout << p2.m_age << " " << *p2.m_height << endl;
}
只需要手动开辟一下即可,这样p1和p2的m_height的指针就指向了堆区不同的两个地址。