This time I'm moving on to little more advanced concepts.
At my school we still use TurboC++, which does not support the string class natively and so I am not able to use its functions easily.
I started with operator overloading and realized that I could use the function strcat(), in order to make my own string class in Turboc++.
What I want to do is basically use the assignment operator '=' to assign strings to a variable just like in Visual C++.
The problem is I really cant figure out the definition of the overloading function, so if anyone could help me out, it would be really helpful.
Note - Please don't say "Just use Visual C++" as I have to create a project and I'm not allowed to use Any other compiler other than Borland
the syntax for overloading operator=() is the following:
1 2 3 4
my_string& mystring::operator=(const my_string& copy)
// code here
Note that you return a reference, in order to be able to chain assignments like so:
a = b = c;
You could also do the following to allow for some_string = "text";:
1 2 3 4
my_string& mystring::operator=(constchar copy)
//copy the parameter to underlying c-string
Also note that it takes a const reference as a parameter. Make sure to check if you need to make the char array larger when you assign new content to a string, so that you don't run into memory problems.
Please do let us know if you need any more help.
Thanks For Helping Out,
If its not too much to ask you you help me out with the function prototype as well.
I was planning on passing two parameters as I have to use strcat() to do the operations. That function takes two arguments so how do I implement that.
my_string& operator=(constchar copy)
my_string& my_string::operator(constchar copy)
//check for sizes, make string_holder bigger if necessary, then make "copy" the content of string_holder
You mentioned you were making a string class yourself - so this is what I assumed. Are you implementing it differently?
I'm not the best at explaining but basically when you call a public function from a class Object say something like obj.output();
Then say you have private variables of obj as something like value.
Then inside your output function you want to access the value of your obj. You can either call this->value or value. This just refers to the object that is calling the function. so to dereference it we would put *this
We are returning a reference to a String in the function earlier so I put return( *this ) to return the lhs value of the operator =.
Basically this is a pointer to the current class instance. It is implictly being using without even putting this-> But if you don't want two of the same variable names you could use that to be safe.