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);
}