Conversion error

Hey,

Trying to get a function to return an array of class String but cannot figure it out. The error is that there is no suitable conversion from String to int. I have no idea how to fix this without messing up the function. Please help. If you need more info let me know.
1
2
3
4
5
6
7
8
9
10
11
 // returns sub string from start to end
int String::substr(int start, int end)const {
	String tmp;
	int j(0);

	for (int i = start; i < end + 1; ++i, ++j) {
		tmp[j] = str[i];
	}
	tmp[end] = '\0';
	return tmp; // conversion error
}
Last edited on
To begin with, your signature is wrong. I'd expect something like:
 
String String::substr(int start, int end) const;


Depending on how String is implemented, This code is almost certainly wrong.
1
2
3
4
	for (int i = start; i < end + 1; ++i, ++j) {
		tmp[j] = str[i];
	}
	tmp[end] = '\0';
They wanted us to implement them as int String substring(int, int)const
but now that I changed it to String String there is no conversion warning for tmp. The code actually works because of the other overloaded operators that I didn't post on here but I need to run a few more tests to make sure everything is alright still. Thanks.
If "they" (who are this mysterious they?) want you to return an int from the function, then what is that int supposed to represent?
"They" are my evil overlords who wish only to torture me with difficult programming problems that get more tedious as the year continues. Seriously though, int represents the return value from a function of my class "String". Changing the function from int String to String::String let me return the value without having to write another function that would convert the return back to String. IDK if that explains it well enough though.
Last edited on
If substr() was changing the state of the object (by storing the string), it couldn't be const. It just makes no sense to return an int. You have to consider how it'll be called.
int represents the return value from a function of my class "String".

Yes, I know it's the return value from the function. I'd have to be incapable of reading a simple function definition, not to know that.

I'm asking you what that value represents. What does it mean? What would it mean if your function returned a 0? What would it mean if it returned a 5? WHat if it returned -3062?

Presumably, "they" told you what this function was supposed to do, and what it was supposed to return? If they were explicit that it had to return an int, then they will have told you what that int is supposed to be.
The code actually works because of the other overloaded operators that I didn't post on here

That implies that either
* String::operator[] acts like append/push_back -- i.e. has automatic reallocation, if necessary
or
* you have undefined behaviour that hasn't bitten your leg off yet

Well, the
tmp[end] = '\0';
is a very strong hint about the latter.
Topic archived. No new replies allowed.