#include "stdafx.h"
#include <iostream>
using namespace std;
class Person {
public:
Person() {
m_pName = nullptr;
m_iAge = 0;
cout << "无参构造函数" << endl;
}
//有参构造函数
Person(char* pName, const int& iAge)
{
if (nullptr != pName)
{
int len = strlen(pName) + 1;
m_pName = new char[len];
memcpy(m_pName, pName, len);
m_iAge = iAge;
cout << "有参构造函数:" << m_pName << ", " << m_iAge << endl;
}
else {
m_pName = nullptr;
m_iAge = 0;
cout << "有参构造函数" << endl;
}
}
浅复制(浅拷贝)构造函数
//Person(const Person& other)
//{
// m_pName = other.m_pName;
// m_iAge = other.m_iAge;
// cout << "浅复制(浅拷贝)构造函数:" << m_pName << ", " << m_iAge << endl;
//}
//深复制(深拷贝)构造函数
Person(const Person& other)
{
if (nullptr != other.m_pName)
{
int len = strlen(other.m_pName) + 1;
m_pName = new char[len];
memcpy(m_pName, other.m_pName, len);
m_iAge = other.m_iAge;
cout << "深复制(深拷贝)构造函数:" << m_pName << ", " << m_iAge << endl;
}
else {
cout << "深复制(深拷贝)构造函数" << endl;
}
}
//赋值构造函数
Person& operator=(const Person& other)
{
if (nullptr != other.m_pName)
{
int len = strlen(other.m_pName) + 1;
this->m_pName = new char[len];
memcpy(this->m_pName, other.m_pName, len);
this->m_iAge = other.m_iAge;
cout << "赋值构造函数:" << m_pName << ", " << m_iAge << endl;
}
else {
cout << "赋值构造函数" << endl;
}
return *this;
}
//C++11添加了右值引用(&&)和移动语义(move)
//&&移动构造函数
Person(Person&& other)
{
if (nullptr != other.m_pName)
{
int len = strlen(other.m_pName) + 1;
m_pName = new char[len];
memcpy(m_pName, other.m_pName, len);
m_iAge = other.m_iAge;
cout << "移动构造函数:" << m_pName << ", " << m_iAge << endl;
}
else {
cout << "移动构造函数" << endl;
}
}
//move移动赋值构造函数
Person& operator=(const Person&& other)
{
if (nullptr != other.m_pName)
{
int len = strlen(other.m_pName) + 1;
this->m_pName = new char[len];
memcpy(this->m_pName, other.m_pName, len);
this->m_iAge = other.m_iAge;
cout << "移动赋值构造函数:" << m_pName << ", " << m_iAge << endl;
}
else {
cout << "移动赋值构造函数" << endl;
}
return *this;
}
//析构函数
~Person() {
if (nullptr != m_pName)
{
delete m_pName;
m_pName = nullptr;
}
cout << "析构函数" << endl;
}
private:
char* m_pName;
int m_iAge;
};
Person fun()
{
cout << "begin-fun()" << endl;
Person person;//局部对象
cout << "begin-fun()" << endl;
return person;
}
int main(int argc, char* argv[])
{
Person a("LiLei", 18); //调用构造函数
Person b(a); //调用复制(拷贝)构造函数
Person c = a; //c是第一次创建,所以调用复制(拷贝)构造函数
Person d; //调用构造函数
d = a; //d是已经存在的对象,所以调用赋值构造函数
Person e = fun(); //如果没有实现[移动构造函数],则调用复制拷贝构造函数;如果实现了,则调用移动构造函数
Person f("WangFang", 19);
Person g;
g = move(f); //调用移动赋值构造函数
system("pause");
return 0;
}
/*
* 关于浅拷贝和深拷贝:
* 浅拷贝:拷贝者和被拷贝者若是同一块地址,则为浅拷贝
* 深拷贝:深拷贝会在堆内存中另外申请一块内寸空间来存储数据
* 默认的拷贝构造函数实现的是浅拷贝,数据成员中有指针时,必须要深拷贝;如果采用浅拷贝,则两个类中的指针指向同一个地址,需要调用两次析构函数,会导致指针悬挂现象
*/
一般的赋值操作就是深拷贝
//int a = 5;
//int b = a;
//
简单的指针指向,就是浅拷贝
//int a = 5;
//int* pa = &a;
//
简单指针的浅拷贝转深拷贝
//int a = 5;
//int* pa = new int;
//*pa = a;
各种构造函数:无参构造函数、带参构造函数、复制(拷贝)构造函数、赋值构造函数、移动构造函数、移动赋值构造函数...
于 2022-07-13 14:35:31 首次发布