Rewrite of the String class

Source: Internet
Author: User
Tags constructor

Header file String.h

Class String
{
Public
String ();
String (char *str);

~string ();
String (const string &other);

String & operator = (const string &other); Assignment function
Friend string operator + (const string &S1, const string &s2);

void display (void);

Private
Char *m_data;
int Len;
};

Implementing File String.cpp
#include "String.h"
#include <iostream.h>
#include <string.h>

String::string ()
{
cout << "No parameter constructor is called" << Endl;

len = 0;
m_data = new Char[1];
M_data[0] = '/0 ';
}

String::string (char *str)
{
cout << "with parameter constructor called" << Endl;

len = strlen (str);
m_data = new Char[len + 1];
strcpy (m_data, str);
}

string::string (const String &other)
{
cout << "Copy constructor is called" << Endl;

len = Other.len;
m_data = new Char[len + 1];

strcpy (M_data, other.m_data);
}

String & string::operator = (const String &other)//Assignment function
{
cout << "overloading = function is called" << Endl;

if (this = = &other)
{
return *this;
}

delete [] m_data;

len = Other.len;
m_data = new Char [len + 1];
strcpy (M_data, other.m_data);

return *this;

}

String::~string ()
{
cout << "destructor is called" << Endl;
delete [] m_data;
}

void String::d isplay ()
{
cout << "M_data=" << m_data << "len =" << len << Endl;
}

String operator + (const string &S1, const string &s2)
{
cout << "overloaded + functions are called" << Endl;

String temp;

Delete Temp.m_data;

Temp.len = S1.len + S2.len;
Temp.m_data = new Char [Temp.len + 1];

strcpy (Temp.m_data, s1.m_data);
strcat (Temp.m_data, s2.m_data);

return temp;
}

Main.cpp

#include "String.h"
#include <iostream.h>

int main (void)
{
String A;
String B ("Hello");
String C (b);
String d ("Ni Hao");
String e;

A.display ();
B.display ();
C.display ();
D.display ();
E.display ();

cout << Endl;

A = D;
A.display ();

cout << Endl;

E = b + D;
cout << "Here" <<endl;
E.display ();

cout << Endl;

return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.