In order for this to work correctly you need to change s
to the member variable pointing to the array of characters. You didn’t provide the class definition of String
so it’s hard to say what the name of that member variable is.
You should also change
char String::element(int i) const
to either
char String::element(size_t i) const
or
char String::element(unsigned int i) const
This is because your array of characters should never be accessed with a negative index value. If you don’t change i
to an unsigned value you need to make sure it’s equal to or greater than zero, which should never be allowed anyway. Toy should also change m_str1
to size_t
or unsigned int
if it already isn’t since the string should never have a negative length.
Applying these suggestions would make String
and element()
look something like the following…
class String
{
unsigned int m_str1; // length of character string
char* m_str; // pointer to the character string
public:
char String::element(unsigned int i) const;
};
char String::element(unsigned int i) const
{
if (i < m_str1)
{
return m_str[i]; // Changed s to m_str
}
cout << "Error" << endl;
return 0;
}
4
solved Stuck on an Implementation for string class [closed]