The question says:
Define the relational operators for Str. In doing so, you will want to know that
the <cstring> header defines a function called strcmp, which compares two character
pointers. The function returns a negative integer if the null-terminated character array
denoted by the first pointer is less than the second, zero if the two strings are equal, or
a positive value if the first string is greater than the second.
I try to build some member function for < but i got stuck:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
class MyString
{
public:
//default constructor, create an empty string
MyString()
{
};
//create a string containing n copies of c
MyString(size_t n, char c) :data(new char[n]), data_length(n)
{
for (size_t i = 0; i < n; i++)
{
data[i] = c;
}
};
//create a string from a null-terminated array
MyString(const char *cp):data(new char[std::strlen(cp)]), data_length(std::strlen(cp))
{
//std::copy(cp, cp + std::strlen(cp), data);
std::copy(cp, cp + std::strlen(cp), stdext::checked_array_iterator<char*>(data, data_length));
}
//destructor
~MyString()
{
//free the array
delete[] data;
};
//relational operator <
bool operator<(const char* rhs)
{
return strcmp(this->data, rhs);
}
private:
size_t data_length;
char* data;
};
|
Inside the main how do I use that?
I tried to code it like that but compiler complains:
1 2 3 4 5 6 7 8 9 10
|
int main()
{
MyString mystr1(3,'a');
MyString mystr2("alon");
if ((mystr1<mystr2))
std::cout << "equal";
return 0;
}
|
Can you give some example how should I implement such a code and how to check it inside the main?