Je reçois un défaut de segmentation et je n'ai aucune idée de comment le déboguer! Il se produit après la création du tableau MyString
, c'est-à-dire le tableau créé sans aucun problème.erreur de segmentation C++
void ConcatTest()
{
cout << "\n----- Testing concatentation on MyStrings\n";
const MyString s[] =
{MyString("outrageous"), MyString("milk"), MyString(""),
MyString("cow"), MyString("bell")};
for (int i = 0; i < 4; i++) {
cout << s[i] << " + " << s[i+1] << " = " << s[i] + s[i+1] << endl;
}
}
donc je pense qu'il peut être quelque chose dans la façon dont je l'opérateur surchargée + ici:
MyString operator+(MyString str1, MyString str2)
{
MyString resultStr = MyString();
delete [] resultStr.pString;
resultStr.pString = new char[strlen(str1.pString) + strlen(str2.pString) + 1];
MyString temp = MyString();
delete [] temp.pString;
temp.pString = new char[strlen(str1.pString) + 1];
strcpy(temp.pString, str1.pString);
delete [] str1.pString;
str1.pString = new char[strlen(str1.pString) + strlen(str2.pString) + 1];
strcpy(str1.pString, temp.pString);
strcat(str1.pString, str2.pString);
strcpy(resultStr.pString, str1.pString);
return resultStr;
}
Toute aide ou des conseils seraient appréciés!
Oui, un "const" pourrait être le bienvenu pour str1 et str2 dans la déclaration de fonction. –
Merci pour l'explication! –