String Class Operations

This is a discussion on String Class Operations within the C++ Programming forums, part of the General Programming Boards category; Is it possible to create a string/char-array class with overloading operations that could preformed these operations?: String = “Hello ” ...

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    162

    Unhappy String Class Operations

    Is it possible to create a string/char-array class with overloading operations that could preformed these operations?:
    String = “Hello ” + “World”;
    Where two constant strings/char-arrays “Hello ” and “World” adds and inserts into the String class. So that the class String will contain the string/char-array "Hello World".
    We haven't inherited Earth from our parents; instead we have borrowed her from our children - old Indian saying.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,651
    No.

    This will work however:
    Code:
    string s = "Hello " " World!";
    gg

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    I guess you could overload = to set the data of the following char* and have it return a reference to itself. Then overload + to add the following char* to itself and have it return a reference to itself. I haven't tested it though.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    Registered User
    Join Date
    Dec 2002
    Posts
    162
    Originally posted by Codeplug
    No.
    This will work however:
    Code:
    string s = "Hello " " World!";
    What type of operation is between the two strings "Hello " and " World!"?



    Originally posted by Magos
    I guess you could overload = to set the data of the following char* and have it return a reference to itself. Then overload + to add the following char* to itself and have it return a reference to itself. I haven't tested it though.
    Could you please demonstrate how this would look like in code?
    Last edited by Aidman; 04-05-2003 at 04:48 PM.
    We haven't inherited Earth from our parents; instead we have borrowed her from our children - old Indian saying.

  5. #5
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,651
    In C and C++, the compiler will automagically concatinate string literals together for you.
    Code:
    string s = "Look at me "
               "I'm a crazy multi-line string "
               "cep'n I ain't!";
    gg

  6. #6
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Thanks to not being able to overide = and + for char* you can't overload them as you wanted. The compiler thinks you're adding or setting pointers, when in fact you want to use your own methods.

    There is a workaround though. If you add parantheses around the string name and the first argument (see code below) it will work. It's ugly, but may be better than nothing :).
    Code:
    #include <iostream>
    using namespace std;
    
    
    //Class declaration
    class String
    {
    	public:
    		//Constructor/Destructor
    		explicit String();
    		~String();
    
    		//Operations
    		String& operator =(const char* NewString);
    		String& operator +(const char* NewString);
    		char* Get();
    
    	private:
    		//Data
    		char* Data;
    
    };
    
    
    //Constructor
    String::String()
    {
    	Data = NULL;
    }
    
    
    //Destructor
    String::~String()
    {
    	if(Data != NULL)
    	{
    		delete[] Data;
    		Data = NULL;
    	}
    }
    
    
    //Set operator
    String& String::operator =(const char* NewString)
    {
    	//Data
    	int Length = 0;
    	char* TempData = NULL;
    
    	//Abort if NewString is NULL
    	if(NewString == NULL)
    	{
    		return *this;
    	}
    
    	//Calculate the string length
    	Length = strlen(NewString);
    
    	//Allocate memory for the new string
    	TempData = new char[Length + 1];
    	if(TempData == NULL)
    	{
    		return *this;
    	}
    
    	//Copy the new string
    	strcpy(TempData, NewString);
    
    	//Deallocate the old string if neccessary
    	if(Data != NULL)
    	{
    		delete[] Data;
    	}
    
    	//Repoint pointers
    	Data = TempData;
    
    	//Return a reference to this object
    	return *this;
    }
    
    
    //Add operator
    String& String::operator +(const char* NewString)
    {
    	//Data
    	int Length1 = 0;
    	int Length2 = 0;
    	char* TempData = NULL;
    
    	//Abort if NewString is NULL
    	if(NewString == NULL)
    	{
    		return *this;
    	}
    
    	//Run = if no previous data exists
    	if(Data == NULL)
    	{
    		return operator =(NewString);
    	}
    
    	//Calculate the string lengths
    	Length1 = strlen(NewString);
    	Length2 = strlen(Data);
    
    	//Allocate memory for the new string
    	TempData = new char[Length1 + Length2 + 1];
    	if(TempData == NULL)
    	{
    		return *this;
    	}
    
    	//Merge the old and new string
    	strcpy(TempData, Data);
    	strcat(TempData, NewString);
    
    	//Deallocate the old string and repoint pointers
    	delete[] Data;
    	Data = TempData;
    
    	//Return a reference to this object
    	return *this;
    }
    
    
    //Returns a pointer to the string
    char* String::Get()
    {
    	return Data;
    }
    
    
    int main()
    {
    	String MyString;
    	(MyString = "Hello world! ") + "How are you? " + "I am fine, thank you...";
    	cout << MyString.Get() << endl;
    
    	return 0;
    }
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  7. #7
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Originally posted by Codeplug
    In C and C++, the compiler will automagically concatinate string literals together for you.
    Code:
    string s = "Look at me "
               "I'm a crazy multi-line string "
               "cep'n I ain't!";
    gg
    He's not talking about string literals, per se. He's asking about creating a string class that has overloaded = and + operators. Here's a string class that I wrote a while back when I was learning about overloaded operators, etc. (with both of those operators and more)

    Code:
    //the header file code
    #pragma once
    
    #include <string.h>
     
    class String
    {
    private:
     char *c;
     int len;
    public:
     String() : c(0), len(0) {}
     String(const char *input);
     ~String();
     void erase();
     const char *str() {return(c);};
     const int size() {return(len);};
     String& operator=(const char *input);
     String& operator=(const String &s);
     String& operator=(const char input);
     String& operator+=(const char *input);
     String& operator+=(const String &s);
     String& operator+=(const char input);
     String& operator--(int i);
     char& operator[](int pos) {return(c[pos]);};
    }; 
    
    //the source file code
    #include "Str.h"
     
    void String::erase()
    {
     if(c)
     {
      delete [] c;
      c=0;
     }
    }
    
    String::String(const char *input)
    {
    	erase();
    	len=strlen(input);
    	if(len>1)
    	{
    		c=new char[len];
    		strcpy(c,input);
    	}
    	else
    	{
    		len=1;
    		c=new char[len];
    		c[0]='\0';
    	}
    }
     
    String::~String()
    {
     erase();
    }
     
    String& String::operator =(const char *input)
    {
    	erase();
    	len=strlen(input)+1;
    	if(len>1)
    	{
    		c=new char[len];
    		strcpy(c,input);
    	}
    	else
    	{
    		len=1;
    		c=new char[len];
    		c[0]='\0';
    	}
    	return(*this);
    }
    
    String& String::operator =(const char input)
    {
    	
    		erase();
    		len=1;
    		c=new char[len];
    		strcpy(c,&input);
    
    	return(*this);
    }
     
    String& String::operator =(const String &s)
    {
    	
    		this->erase();
    		this->len=s.len;
    		this->c=new char[this->len];
    		strcpy(this->c,s.c);
    
    	return(*this);
    }
     
    String& String::operator +=(const char *input)
    {
    	
    		char *temp=new char[len];
    		len+=strlen(input);
    		
    		strcpy(temp,c);
    		
    		erase();
    		c=new char[len];
    		
    		strcpy(c,temp);
    		strcat(c,input);
    
    	return(*this); 
    }
    
    String& String::operator +=(const char input)
    {
    		char *temp=new char[len];
    		len++;
    		strcpy(temp,c);
    		erase();
    		c=new char[len];
    		strcpy(c,temp);
    		strcat(c,&input);
    	
    	return(*this);
    }
     
    String& String::operator +=(const String &s)
    {
    	
    		char *temp=new char[this->len];
    		this->len+=s.len+1;
    		strcpy(temp,this->c);
    		this->erase();
    		this->c=new char[this->len];
    		strcpy(this->c,temp);
    		strcat(this->c,s.c);
    
    	return(*this);
    }
    
    String& String::operator --(int i)
    {
    		if(len>=1)
    	{
    		char *temp;
    		int i;
    		len--;
    		temp=new char[len];
    		for(i=0;i<(len-1);i++)
    		{
    			temp[i]=c[i];
    		}
    		erase();
    		c=new char[len];
    		for(i=0;i<(len-1);i++)
    		{
    			c[i]=temp[i];
    		}
    		c[len-1]='\0';
    	}
    	return(*this);
    }

  8. #8
    Registered User
    Join Date
    Dec 2002
    Posts
    162
    He's asking about creating a string class that has overloaded = and + operators.
    Yes partly that, but also how to combind this operation so that you can preform this operation: String = "Hello " + "World";
    Is it possible to do that your class you posted?



    (MyString = "Hello world! ") + "How are you? " + "I am fine, thank you...";
    So in other words, atleast one of the parameters in the + operation must by pointing to a class String? So it isn't possible to preform these operations?: String = "Hello " + "World";
    Last edited by Aidman; 04-05-2003 at 11:07 PM.
    We haven't inherited Earth from our parents; instead we have borrowed her from our children - old Indian saying.

  9. #9
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Originally posted by Aidman
    So in other words, atleast one of the parameters in the + operation must by pointing to a class String? So it isn't possible to preform these operations?: String = "Hello " + "World";
    As I explained, it works in theory. However, the compiler believes you're trying to add two char pointers when doing this: "Hello " + "world!" instead of using the overloaded operators, thus the problems.
    It has to do with + having higher priority than =. Using parantheses, the = will be executed first thus making things work properly.

    When typing this:
    Code:
    MyString = "Hello world! " + "How are you? " + "I am fine, thank you...";
    It will be executed in this order:
    Code:
    (MyString = (("Hello world! " + "How are you? ") + "I am fine, thank you..."));
    As you see, the pointers are added first, then the assignment is executed. Not good, since you can't overload char* + char*.

    In this code however:
    Code:
    (MyString = "Hello world! ") + "How are you? " + "I am fine, thank you...";
    Thanks to the parantheses, you force the assignment operator to be executed first, and since it returns a reference to itself the rest of the + operators will be executed properly:
    Code:
    (((MyString = "Hello world! ") + "How are you? ") + "I am fine, thank you...");
    Last edited by Magos; 04-06-2003 at 06:17 AM.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  10. #10
    Registered User
    Join Date
    Dec 2002
    Posts
    162
    Ok Thanks
    We haven't inherited Earth from our parents; instead we have borrowed her from our children - old Indian saying.

  11. #11
    Registered User
    Join Date
    May 2002
    Posts
    49

    That's easy

    string str = string("Hello, ") + "World!" + " Some other words.";

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 04:01 PM
  4. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  5. class object manipulation
    By guda in forum C++ Programming
    Replies: 2
    Last Post: 10-09-2004, 10:43 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21