[翟旭][面向对象程序设计]拷贝构造不可值传递

上一个稿子是L写的, 幽默不是我的风格, 冷酷才是

深拷贝

class A
{
public:
	A()
	{
		cout << "无参" << endl;
	}
	A(int age, int height)
	{
		this->m_age = age;
		this->m_height = new int(height);
		cout << "有参" << endl;
	}
	A(const A& a)
	{
		this->m_age = a.m_age;
		this->m_height = new int(*(a.m_height));
	}

	~A()
	{
		cout << "yuzujr" << endl;
		if (this->m_height != nullptr)
		{
			delete this->m_height;
			this->m_height = 0;
		}
	}

private:
	int m_age;
	int* m_height;
};

int main()
{
	A a1(12, 12);
	A a2(a1);
}

正确代码如上;

并不是说有拷贝构造代码就不需要有参构造了. 仍然需要用有参构造参数来初始化.

这里新添加的代码是

A(const A& a)
	{
		this->m_age = a.m_age;
		this->m_height = new int(*(a.m_height));
	}

编译器有自带的拷贝构造函数, 但属于浅拷贝, 所以我们需要重载.

浅拷贝的问题

class B
{
public:
	B(int age,int height)
	{
		this->m_age = 1000;
		pHeight = new int(height);
	}

	~B()
	{
		cout << "yuzujr\a" << endl;
		if (this->pHeight != nullptr)
		{
			delete pHeight;
			pHeight = 0;
		}
	}
private:
	int m_age;
	int* pHeight;
};

int main()
{
	B b1(123412, 1234);
	B b2(b1);
}

这个运行结果是我预期的. 堆区内容重复释放导致崩溃.

为什么拷贝构造不能值传递

若是传值的话 实参a1 传给形参 p_a 时,调用的还是拷贝构造函数
那相当于拷贝构造函数在执行的时候调用了自己,产生了一个递归,死循环;
拷贝构造函数不能传值,传指针和引用就不会存在这个问题

也可以说:

不能传值是因为传值的过程中,形参是实参的一份拷贝.
我们的参数是一个对象,此时编译器调用拷贝构造函数.
如果传值的话,我们在实现拷贝构造函数时需要调用拷贝构造函数复制实参,此时还未定义拷贝构造函数,就会陷入无穷递归…

6个默认成员函数

1. 构造函数

2. 析构函数

3. 拷贝构造函数

4. 赋值运算符函数

5. 普通取地址符重载(5, 6代码如下)

6. const类型取地址符重载

class A
{
public:
	A* operator&()
	{
		return this;
	}

	const A* operator&()const
	{
		return this;
	}
};

下面看

#include<iostream>
using namespace std;

class A
{
public:
	/*A* operator&()
	{
		return this;
	}

	const A* operator&()const
	{
		return this;
	}*/
};
int main()
{
	A asd;
	cout << &asd;
}
#include<iostream>
using namespace std;

class A
{
public:
	A* operator&()
	{
		return this;
	}

	const A* operator&()const
	{
		return this;
	}
};
int main()
{
	A asd;
	cout << &asd;
}

这俩玩意没啥区别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青樱部_OFFICIAL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值