CMJCPP
CMJCPP
2017-09-25 04:50

C++ 出现Debug Assertion Failed 怎么解决 求教

  • strlen
  • c++
  • 调试
  • string
  • ios

#include
#ifndef STRINGBAD_H_
#define STRINGBAD_H_
class StringBad
{
private:
char * str;
int len;
static int num_strings;

public:
StringBad(const StringBad & st);

StringBad(const char * s);

StringBad();

~StringBad();

friend std::ostream & operator<<(std::ostream & os,const StringBad & st);

StringBad & operator=(const StringBad & st);

};
#endif

#include
#include"stringbad.h"
using std::cout;

int StringBad::num_strings = 0;

StringBad::StringBad(const StringBad & st)

{
num_strings++;

len = st.len;

str = new char[len + 1];

strcpy_s(str, sizeof(st.str),st.str);

cout<< num_strings << ": \"" << str

<< "\" object created\n";
}

StringBad::StringBad(const char * s)
{
len = std::strlen(s);

str = new char[ len + 1 ];

strcpy_s(str,sizeof(s), s);

num_strings++;
cout << num_strings << ": \"" << str
<< "\" object created\n";
}

StringBad::StringBad()
{

//char s[4] = "C++";
len = 4;
str = new char[4];
//strcpy_s(str, sizeof(s),s);
num_strings++;
cout << num_strings << ": \"" << str
    << "\" default object created\n";

}

StringBad::~StringBad()
{
cout << "\"" << str << "\" object deleted, ";
--num_strings;
cout << num_strings << " left\n";
delete[]str;
}

std::ostream & operator<<(std::ostream & os, const StringBad & st)
{
os << st.str;
return os;
}

StringBad & StringBad::operator=(const StringBad & st)
{
if (this == &st)

return *this;

delete[]str;

len = st.len;

str = new char[len + 1];

strcpy_s(str, sizeof(st.str), st.str);

return *this;
}

![图片说明](https://img-ask.csdn.net/upload/201709/25/1506314988_264230.png)
#include<iostream>

using std::cout;
#include"stringbad.h"

void callme1(StringBad &);
void callme2(StringBad);

int main()
{
using std::endl;
{
cout << "Starting an inner block.\n";
StringBad headline1("Celery Stalks at Midnight");
StringBad headline2("Lettuce Prey");
StringBad sports("Spinach Leaves Bowl for Dollars");
cout << "headline1: " << headline1 << endl;
cout << "headline2: " << headline2 << endl;
cout << "sports: " << sports << endl;
callme1(headline1);
cout << "headline1: " << headline1 << endl;
callme2(headline2);
cout << "headline2: " << headline2 << endl;
cout << "Initialize one object to another:\n";
StringBad sailor = sports;
cout << "sailor: " << sailor << endl;
cout << "Assign one object to another:\n";
StringBad knot;
knot = headline1;
cout << "knot: " << knot << endl;
cout << "Exiting the block.\n";
}
cout << "End of main()\n";

return 0;

}

void callme1(StringBad & rsb)
{
cout << "String passed by reference:\n";
cout << " \"" << rsb << "\"\n";
}

void callme2(StringBad sb)
{
cout << "String passwd by value:\n";
cout << " \"" << sb << "\"\n";
}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答