I am trying to implement my own CString class. I am facing some problem in shallow copying the pointer. Here is the class
#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]='\0';
}
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]='\0';
}
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]='\0';
}
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]='\0';
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]!='\0'){
i++;
}
return i;
}
char *m_value;
};
ostream& operator<<(ostream& os, myCString obj)
{
os<<obj.m_value;
return os;
}
and here is the main():
#include"myCString.h"
int main()
{
myCString *ptr = new myCString("Hi! This is myCString\n");
cout<<*ptr;
myCString *ptr2 = ptr;
delete ptr;
cout<<*ptr2;
delete ptr2;
return 0;
}
The issue is when shallow copy happens; i know that writing
myCString *ptr2 = new myCString(ptr);
will fix the issue; but i want to keep the main function intact and make some changes in the class. Is there anyway i can do it? Thanks in advance.
将您的myCString(char* strParam)
签名更改为
myCString(const char* strParam)
Your request is to make a deep copy of the objekt in the line myCString *ptr2 = ptr
, but this aim is not reachable by object's class programing, because this line only copies a pointer and does not involve the object's class. If you like to call the copy constructor, You must write as You suggested: myCString *ptr2 = new myCString(ptr)
; or You can write:
myCString mystr("Hi! This is myCString\n");
cout<<mystr;
myCString mystr2 =mystr;
cout<<mystr;
Another problem: calling function ostream& operator<<(ostream& os, myCString obj)
the copy operator myCString(const myCString& obj)
is called for parameter obj. You should write
ostream& operator<<(ostream& os, const myCString& obj)
to avoid this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.