#include <string.h> #include <stdio.h> class CString{ public: CString(){value = NULL;} CString(char *initValue){ if(initValue != NULL) value = NULL; else strcpy((value = new char[strlen(initValue)+1]),initValue); } ~CString(){if(value != NULL) delete [] value;} CString& operator=(char* newValue){ if(value != NULL) delete [] value; if(newValue != NULL) value = NULL; else strcpy((value = new char[strlen(newValue)+1]),newValue); } CString& operator=(CString& newValue){ if(value != NULL) delete [] value; if(newValue.value != NULL) value = NULL; else strcpy((value = new char[strlen(newValue.value)+1]),newValue.value); } CString operator+(char *addValue){ CString tempValue; strcpy((tempValue.value = new char[strlen(value) + strlen(addValue) + 1]),value); strcat(tempValue.value,addValue); return CString(tempValue.value); } CString operator+(CString& addValue){ CString tempValue; strcpy((tempValue.value = new char[strlen(value) + strlen(addValue.value) + 1]),value); strcat(tempValue.value,addValue.value); return CString(tempValue.value); } char *value; }; int main(int argc, char *argv[]) { CString a("First String"), b("Second String"), c; c = a + " - " + b; printf(c.value); }
The compiler is right: operator+ returns a *temporary* CString and you have an assignment operator taking a *non const* reference. Just change the latter to take a const reference.
The reason I was passing the reference and not the value is because is some circumstances I can change the value of the parameter. Using the const keyword prevents me from calling methods that can change the value – even if in this example they do not. Thanks, Dallas Clarke BSc (CS) LLB UNSW Architect / Lead Developer Ekky Software Website: http://www.ekkySoftware.com
You need to change the operator= to: CString& operator=(const CString& newValue){ Otherwise you cannot bind a rvalue to the reference as it will only bind to a lvalue and returned from operator+ is a rvalue. In C++0x there are rvalue references which you can use but that feature is not in a released version of GCC yet. (it is on the trunk though).