【发布时间】:2017-01-25 15:12:02
【问题描述】:
当我运行我的程序时,会出现一个带有“Debug Assertion Failed”消息的窗口。
源.cpp
#include <iostream>
#include "Header.h"
using namespace std;
String :: String ()
{
this->s=new char[50];
}
String :: String(char *sir)
{
this->s=new char[strlen(sir)+1];
strcpy_s(this->s, strlen(sir)+1, sir);
}
String :: ~String()
{
delete [] s;
}
String& String:: operator=(String &sir)
{
strcpy_s(this->s, strlen(sir.s)+1, sir.s);
return *this;
}
String String:: operator+(String sir)
{
String rez;
rez.s=new char [strlen(s)+strlen(sir.s)+1];
strcpy_s(rez.s, strlen(s)+1,s);
strcat_s(rez.s, strlen(s)+strlen(sir.s)+1, sir.s);
return rez;
}
void String:: afisare()
{
cout << s<< endl;
}
bool String:: operator==(String sir)
{
if(strcmp(s, sir.s)==0)
return true;
else
return false;
}`
Main.cpp
#include <iostream>
#include "Header.h"
using namespace std;
int main()
{
String sir1("John ");
String sir2("Ola ");
String rez;
if(sir1==sir2)
cout << "string are identicaly"<< endl;
else
cout << "strings are not identicaly"<< endl;
rez=sir1+sir2; // this line i have debug assertion failed
rez.afisare();
return 0;
}
【问题讨论】:
-
String& String:: operator=(String &sir)当strlen(sir.s)+1长于this->s时会发生什么 -
了解三/五/零规则。
-
您还缺少复制构造函数。
String(const String &sir). -
在使用符号
String和使用using namespace std;时要非常小心,实际上我建议将using全部去掉。 -
好东西
std::string是小写的。会不会有冲突??
标签: c++ string oop assertions