I am asked to create a Substring() method that returns a substring of the original string which begins at location start and is as long as length
Here is how I attempted to implement the function in my .cpp file:
MyString sub;
sub = new char[length];
for(int i = start; i <length; i++)
{
sub[i] = this[i];
}
return sub;
and I got this error:
error: expected unqualified-id before
[token
MyString.cpp:206: error: no match foroperator[]insub[i]
Note: I am not supposed to overload [].
MyString is the defined class.
What exactly am I doing wrong?
It simply means that this.substr() is not valid C++.
this is a pointer to the current object. So unless the method MyString::substr() exists, you can’t do that.
Starting from that, I don’t know which members there are in your MyString class. If there is a std::string, you can use the substr method on it. f the underlying member is just a char*, you will have to use simple array and c-string operations on it to extract a subtring from it.
With an exemple. If your class is like this
Then your Substring method will be like this:
On the other hand, if your class MyString is like that:
Then your method will be like this:
EDIT : If we look at the code you provided (after last edit), it seems that you are actually using an underlying char*. So let’s have a look at what you wrote^^
What you want to do is actually modify the characters of the underlying char*. So what you should have done is:
So instead of creating a new MyString, you will create a new char*. You can’t directly assign a char* to a MyString (or at least, it’s what I think). Now, let’s look a the other part of your code:
this is a pointer to MyString. So this[i] is equivalent to this.operator which is incalid since this is a pointer. You can’t have this followed by a dot. However, if you had written this->operator, it would have searched for a function like char& MyString::operator[](int i). Since you did not defined this function, you would still have a compiler error (it’s also the one you currently have for sub[i] since you defined sub as a MyString. You should write:
But it’s still provided _str is a char* in your class. Then you will be able to finish your function by:
But there, it’s provided that your MyString class has a constructor that takes a char* as a parameter 🙂