上一个稿子是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;
}
这俩玩意没啥区别