C++ 学习笔记 16 对象的拷贝

#include<iostream>

//1. 原始类型拷贝(栈空间)
void prototypeCopyStack() {
	int a = 1;
	//将a的值拷贝给b,而不是将b指向a
	int b = a;  //拷贝新对象
	b = 3;
	std::cout << a << " | " << b << std::endl;
}

struct Vecter2 {
	int x, y;
};

//2. 结构体拷贝(栈空间)
void structCopyStack() {
	Vecter2 v1 = { 2, 3 };
	Vecter2 v2 = v1;	//拷贝新对象
	v2.x = 6;
	std::cout << v1.x << " | " << v1.y << std::endl;
	std::cout << v2.x << " | " << v2.y << std::endl;
}

//3. 结构体拷贝(堆空间)
void structCopyHeap() {
	Vecter2* v1 = new Vecter2{ 2, 3 };
	Vecter2* v2 = v1;	//指针执行同一对象,未拷贝
	v2->x = 6;
	std::cout << v1->x << " | " << v1->y << std::endl;
	std::cout << v2->x << " | " << v2->y << std::endl;
}


//对象拷贝,对对象内部的引&指针用数据的数据new深拷贝
class MyString {
private:
	char* m_Buffer;
	unsigned int m_Size;
public:
	//自定义实现
	MyString(const char* string) {
		std::cout << "String构造1" << std::endl;
		m_Size = strlen(string);
		//保障新对象的数据指向新的堆空间,与原来数据不共享
		m_Buffer = new char[m_Size + 1];
		//拷贝赋值
		memcpy(m_Buffer, string, m_Size);
		m_Buffer[m_Size] = 0;
	}

	//const保证只读,引用保证不复制
	MyString(const MyString& other):
		m_Size(other.m_Size)
	{
		std::cout << "String深拷贝构造" << std::endl;
		//保障新对象的数据指向新的堆空间,与原来数据不共享
		m_Buffer = new char[m_Size + 1];
		//拷贝赋值
		memcpy(m_Buffer, other.m_Buffer, m_Size + 1);
	}

	~MyString() {
		delete[] m_Buffer;
	}

	//返回值类型保证是取址而不是复制
	char& operator[](unsigned int index) {
		return m_Buffer[index];
	}

	friend std::ostream& operator<<(std::ostream& stream, const MyString& string);
};

//重定义输出 MyString 数据
std::ostream& operator<<(std::ostream& stream, const MyString& string) {
	stream << string.m_Buffer;
	return stream;
}

//控制台输出
void PrintString(const MyString& string) {
	std::cout << string << std::endl;
}

int main() {
	//prototypeCopyStack();
	//structCopyStack();
	//structCopyHeap();

	MyString s1("Cherno");
	PrintString(s1);

	MyString s2 = s1;
	PrintString(s2);

	std::cin.get();
}
posted @ 2025-12-11 10:19  超轶绝尘  阅读(0)  评论(0)    收藏  举报