#include <iostream>
#include <cstring>
using namespace std;
class String
{
private:
char *ptr;
public:
String();
String(char* s);
~String();
operator char*() { return ptr; }
int operator==(const String &other);
};
int main()
{
String a("STRING 1");
String b("STRING 2");
cout << "The value of a is: " << endl;
cout << a << endl;
cout << "The value of b is: " << endl;
cout << b << endl;
return 0;
}
String::String()
{
ptr = new char[1];
ptr[0] = '\0';
}
String::String(char* s)
{
int n = strlen(s);
ptr = new char[n + 1];
strcpy(ptr, s);
}
String::~String()
{
delete [] ptr;
}
int String::operator==(const String &other)
{
return (strcmp(ptr, other.ptr) == 0);
}
In the program above I have a few questions.
My C++ book says that this line operator char*() { return ptr; }
is what allows an object of this clas to be used with the stream operators << & >>. How is this since neither << nor >> are anywhere in that line as in other operator methods? Also, how is it that this operator does not show a return type before the method name, it just says operator?
My second questions is this line return (strcmp(ptr, other.ptr) == 0);
these short hand line have always confused me. I believe this to be. if(strcmp(ptr, other.ptr) == ture) return 0;
is that understanding correct?