使用复制构造函数进行深度复制
deep copying using copy constructor c++
我正在尝试实现我自己的CString类。我在浅拷贝指针时遇到了一些问题。这是类
#include<iostream>
#include<string.h>
using namespace std;
class myCString{
public:
myCString(){
m_value = NULL;
}
myCString(char* strParam){
int len = length(strParam);
m_value = new char[len+1];
for(int i=0;i<len; i++)
{
m_value[i] = strParam[i];
}
m_value[len]=' ';
}
myCString(const myCString& obj)
{
int len = obj.length();
m_value = new char[len+1];
for(int i=0;i<len; i++)
{
m_value[i] = obj.m_value[i];
}
m_value[len]=' ';
}
myCString(const myCString *obj)
{
int len = obj->length();
m_value = new char[len+1];
for(int i=0;i<len; i++)
{
m_value[i] = obj->m_value[i];
}
m_value[len]=' ';
}
const int length() const
{
return length(m_value);
}
myCString operator=(myCString obj)
{
int i=0;
int length= obj.length();
m_value = new char[length + 1];
for(;i<obj.length(); i++)
{
m_value[i] = obj.m_value[i];
}
m_value[length]=' ';
return m_value;
}
~myCString()
{
delete []m_value;
m_value = NULL;
}
friend ostream& operator<<(ostream& os, const myCString obj);
private:
const int length(char* strParam)const
{
int i=0;
while(strParam[i]!=' '){
i++;
}
return i;
}
char *m_value;
};
ostream& operator<<(ostream& os, myCString obj)
{
os<<obj.m_value;
return os;
}
,这里是main():
#include"myCString.h"
int main()
{
myCString *ptr = new myCString("Hi! This is myCStringn");
cout<<*ptr;
myCString *ptr2 = ptr;
delete ptr;
cout<<*ptr2;
delete ptr2;
return 0;
}
问题是当浅拷贝发生时;我知道写
myCString *ptr2 = new myCString(ptr);
将修复这个问题;但是我想保持main函数的完整性,并在类中做一些改变。有什么办法可以让我做吗?
您的请求是对myCString *ptr2 = ptr
行中的对象进行深度复制,但是对象的类编程无法达到这个目的,因为这一行只复制一个指针,不涉及对象的类。如果你想调用复制构造函数,你必须按照你的建议写:myCString *ptr2 = new myCString(ptr)
;或者你可以这样写:
myCString mystr("Hi! This is myCStringn");
cout<<mystr;
myCString mystr2 =mystr;
cout<<mystr;
另一个问题:调用ostream& operator<<(ostream& os, myCString obj)
函数对参数obj调用复制操作符myCString(const myCString& obj)
。你应该写
ostream& operator<<(ostream& os, const myCString& obj)
myCString(char* strParam)签名到>
myCString(const char* strParam)
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- C++尝试深度复制唯一指针时出现内存访问冲突
- 在 c++ 中使用深度复制的运算符重载
- 如何深度复制链表对象指针
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 如何将结构深度复制到向量的每个元素
- 我需要做一个深度复制,我是否正确使用了我的复制构造函数?
- 是否可以在不显式迭代每个元素的情况下深度复制指针容器?
- 如何深度复制unique_ptr向量
- 二叉搜索树 深度复制和取消引用
- 是否有 pybind11::array_t 的(深度)复制构造函数
- 链表的这个别名运算符是否会产生深度复制
- 有没有一种 stl 方法来执行指针向量的深度复制
- cv::P oint3f 赋值运算符是否执行"深度"复制?
- Qt:通过深度复制访问列表中的数据结构是否应该比通过指针访问它慢得多
- 深度复制包含引用成员(C++)的结构
- 如何将“char *”深度复制到std::stringstream
- 如何在双向链表上执行深度复制
- 在复制构造函数中执行深度复制
- 深度复制cv::垫子替代品,哪个更好?