mercredi 25 mars 2015

Objects not being returned the way I intend, could use some insight

so I'm building a string class and I am having difficulty displaying a certain return statement. Here is some of the code:


Part in main my program crashes(method call):



cout << "s5.substring(10,16) = " << s5.substring(10,16) << '\n';


method definition:



MyString MyString::substring(unsigned int sub1, unsigned int subLength) const
{
MyString temp = new char[subLength + 1];
int count = 0;
for(int i = sub1; i <= sub1 + subLength; i++){
temp[count] = mystr[i];
count++;
}
temp[subLength] = '\0';
cout << "temp: " << temp.mystr;
return temp.mystr;
}


the cout temp statement actually does print out the correct statement its just when I need to use it in the main function call, it crashes.


Here is the extraction operator overloaded(possible issue here?):



ostream& operator<< (ostream& os, const MyString& s)
{
os << s.mystr;
return os;
}


I have an inkling that the error lies here, but then again, this causes no other problems in the code as far as I am aware. Hoping someone can lead me in the right direction, or point something blatantly wrong.


**EDIT: Gonna add my constructors in case that helps parse the code at all:



MyString::MyString()
{
//need to have null character
size = 1;
mystr = new char[size];
mystr[size-1] = '\0';

}
// conversion from c-string
MyString::MyString(const char* str )
{
//add one to string for null character
size = strlen(str) + 1;
mystr = new char[size];
for (int i = 0; i < size; i ++)
mystr[i] = str[i];
mystr[size - 1] = '\0';
}


FINAL EDIT: no one will probably see this, but I finally got it, listening to @whozcraig helped me see that i needed to make temp into a char array and then do all the seetting and then create a new mystring, set that guy up, and then delete temp and return the new mystring object


Aucun commentaire:

Enregistrer un commentaire