I am stuck on this part that i am posting. It's just eating me alive. I am trying to make the private pointer data == a given string, but nothing i try works. I have provided the functions needed to test the problem function, and the header file.
//************************MString.cpp***********
#include "Mstring.h"
#include <iostream.h>
#include <cstring>
#include <cstddef>
//----->I am stuck on this function<------------
const MString& MString:perator= (const char *p)
//needs to be fixed
//Postcondition: data[] == p[] and length==strlen(p),returns MString
{
MString temp;
temp.length=strlen(p);
delete [] temp.data;
temp.data=new char[temp.length+1];
for (int i=0; i<temp.length+1; i++)
temp.data[i]=p[i];
return temp;
}
//---------------> stuck on above function----------------
MString:: MString()
//constructor
//Postcondition: length==0 and data ==NULL
{
length=0;
data=new char;
*data=NULL;
}
MString::MString(const char *p)
//constructor
//Postcondition: length == length of *p and *p is copied to data
{
length=strlen(p);
data=new char[length+1];
strcpy(data,p);
//for(int i=0; i<length+1; i++)
// data[i]=p[i];
}
MString::MString(const MString& copy)
//copy constructor
//Postcondition: length==copy.length and data points to a duplicate of copy's data
{
length=copy.length;
data=new char[length+1];
strcpy(data,copy.data);
//for(int i=0; i<length+1; i++)
// data[i]=copy.data[i];
}
MString::~MString()
//destructor
//Postcondition: deletes string
{
delete [] data;
}
int MString::Length() const
//Postcondition: returns length of string
{
return length;
}
ostream & operator << (ostream & out, const MString &o)
//overloaded cout operator
//Postcondition: preforms cout for class MString
{
for(int i=0; i<o.length+1; i++)
out << o.data[i];
return out;
}
//*****************client.cpp*************
int main()
{
//construction
MString s1;
MString s2("Hello world");
//*********This part does not work***********
//overloaded assignment
s1 = "C style string";
cout << s1 << endl;
// output: C style string
cout << s1.Length() << endl;
// output: 14
cout << s2 << endl;
// output: Hello world
return 0;
}
//**************MString.h***************
#include <iostream.h>
class MString
{
//input, output
friend ostream & operator << (ostream & out, const MString &);
private:
char * data;
int length;
public:
//constructors
MString();
MString(const char *p);
MString(const MString& copy);
//destructor
~MString();
//length method
int Length() const;
//overloaded assignment
const MString& operator= (const char *);
};