Help understanding how "operator char*()" works.
Hello, everyone!
Sorry to be a bother, but I needed some help wrapping my head around some syntax.
I would like to apologize in advance for the long post.
The book I'm reading from right now is trying to teach me how to make a class similar to #include <string>. However, there is some strange syntax that I'm not understanding.
I've never posted here before, much less posted code, so please forgive me if I don't provide all the information you need.
Also, I'm fairly new at programming. I've only been learning this for about 5 months or so.
Code:
class my_string {
private:
char *ptr;
public:
//Constructors and destructors that I understand, and functions I understand, so I
//see no need to post any of the code I do understand.
my_string& operator=(const my_string &object)
{cpy(object.ptr); return *this;}
my_string& operator=(char *s)
{cpy(char *s); return *this;}
operator char*() {return ptr;}
void cpy(char *s)
};
void my_string::cpy(char *s) {
delete [] ptr;
int n = strlen(s);
ptr = new char[n + 1];
strcpy(ptr, s);
}
I don't understand why it is written this way:
Code:
my_String& operator=(const my_string &object);
I know "&object" is a reference, but I don't fully understand what "my_string&" means, is it referencing something? If it is then what is it referencing? If it's something other than a reference, can someone please explain what it means? Also, why is there only one definition of cpy? and not something like:
Code:
void cpy(char *s);
void cpy(const my_string &object);
also I don't understand exactly how:
works. I know it has something to do with converting the "my_string" object to a char*(ptr) for use with cout, but I don't understand exactly how.
Anyways, thank you to anyone who takes the time to answer this, and I apologize if this is something simple. I'm learning on my own, so I don't have a teacher or professor to ask. If I didn't provide enough information, or ask my questions in any coherent way, please let me know so I can try to clarify what I'm asking.