Tuesday, February 24, 2015

Copy Constructor for a String class

String.h


#ifndef STRING_H
#define STRING_H
#include "List.h"

class String{
public:
    String();
    ~String();
    String(const String&);
    String(const char*);
    String(List<char> &copy);
    String& operator=(const String &copy);
    const char* c_str() const;
protected:
    char * entry;
    int length;
};
    static bool operator==(const String &first, const String &second);
    static bool operator>(const String &first, const String &second);
    static bool operator<(const String &first, const String &second);
    static bool operator>=(const String &first, const String &second);
    static bool operator<=(const String &first, const String &second);
#endif


String.CPP


#ifndef STRING_CPP
#define STRING_CPP
#include "String.h"
#include <string>
using std::string;

String::String(){
//  entry = NULL;
    length = 0;
}

String::~String(){
    delete entry;
}

String::String(const String &string1 ){
    length = strlen(string1.c_str());
    entry = new char[length+1];
    for (int i=0;i<length;i++)
        entry[i] = string1.c_str()[i];
    entry[length] = '\0';
}

String& String::operator=(const String &copy){
    length = strlen(copy.c_str());
    entry = new char[length+1];
    for (int i=0;i<length;i++)
        entry[i] = copy.c_str()[i];
    entry[length] = '\0';
    return (*this);
}

String::String(const char * CharToString){
    length = strlen(CharToString);
    entry = new char[length+1];
    strcpy_s(entry,length, CharToString);
}

String::String(List<char> &ListChar){
    length = ListChar.Size();
    entry = new char[length+1];
    for (int i=i;i<length;i++)
        ListChar.Retrieve(entry[i],i);
    entry[length] = '\0';
}

const char * String ::c_str() const{
    return (const char*) entry;
}

 static bool operator==(const String &first, const String &second){
    return strcmp(first.c_str(),second.c_str()) == 0;
}

 static bool operator <(const String &first, const String &second){
    return (strcmp(first.c_str(),second.c_str()) < 0);
}

 static bool operator >(const String &first, const String &second){
    return (strcmp(first.c_str(),second.c_str()) > 0);
}

static bool operator <=(const String &first, const String &second){
    return (strcmp(first.c_str(),second.c_str()) <= 0);
}

static bool operator >=(const String &first, const String &second){
    return (strcmp(first.c_str(),second.c_str()) >= 0);
}


#endif

No comments:

Post a Comment