StringBad.h
#include <iostream>
#ifndef STRINGBAD_H
#define STRINGBAD_H
class StringBad
{
private:
char* str;
int len;
static int num_string;
public:
StringBad();
StringBad(const char* s);
~StringBad();
friend std::ostream& operator<<(std::ostream& os,const StringBad& st);
};
#endif
StringBad.cpp
#include "./StringBad.h"
#include <cstring>
using namespace std;
int StringBad::num_string = 0;
StringBad::StringBad(const char* s)
{
len = strlen(s);
str = new char[len+1];
strcpy(str,s);
num_string++;
cout << num_string << ":" << str << "对象被创建" << endl;
}
StringBad::StringBad()
{
len = 4;
str = new char[4];
strcpy(str,"C++");
num_string++;
cout << num_string << ":" << str << "对象被创建" << endl;
}
StringBad::~StringBad()
{
cout << str << "对象被销毁,\t" ;
--num_string;
cout << num_string << "个对象存在" << endl;
delete []str;
}
std::ostream& operator <<(std::ostream& os,const StringBad& st)
{
os << st.str;
return os;
}
main.cpp
#include <iostream>
#include "StringBad.h"
using namespace std;
void callme1(StringBad& st)
{
cout << "引用传递:" << st << endl;
};
void callme2(StringBad st)
{
cout << "值传递:" << st << endl;
};
int main()
{
StringBad st1("张飞");
StringBad st2("李四");
StringBad st3("王五");
callme1(st1);
cout << "输出st1:" << st1 << endl;
callme2(st2);
cout << "输出st2:" << st2 << endl;
StringBad st4 = st3;
StringBad st5;
st5 = st1;
}
改进后的StringBad类
StringBad.h
#include <iostream>
#ifndef STRINGBAD_H
#define STRINGBAD_H
class StringBad
{
private:
char* str;
int len;
static int num_string;
public:
StringBad();
StringBad(const char* s);
StringBad(const StringBad& st);
~StringBad();
StringBad& operator=(const StringBad& st);
friend std::ostream& operator<<(std::ostream& os,const StringBad& st);
};
#endif
StringBad.cpp
#include "./StringBad.h"
#include <cstring>
using namespace std;
int StringBad::num_string = 0;
StringBad::StringBad(const char* s)
{
len = strlen(s);
str = new char[len+1];
strcpy(str,s);
num_string++;
cout << num_string << ":" << str << "对象被创建" << endl;
}
StringBad::StringBad()
{
len = 4;
str = new char[4];
strcpy(str,"C++");
num_string++;
cout << num_string << ":" << str << "对象被创建" << endl;
}
StringBad::StringBad(const StringBad& st)
{
cout << "调用复制构造" << endl;
num_string++;
len = st.len;
str = new char[len+1];
strcpy(str,st.str);
cout << num_string << ":" << str << "对象被创建" << endl;
}
StringBad::~StringBad()
{
cout << str << "对象被销毁,\t" ;
--num_string;
cout << num_string << "个对象存在" << endl;
delete []str;
}
StringBad& StringBad::operator=(const StringBad& st)
{
if(this == &st)
return *this;
delete [] str;
len = st.len;
str = new char[len+1];
strcpy(str,st.str);
return *this;
}
std::ostream& operator <<(std::ostream& os,const StringBad& st)
{
os << st.str;
return os;
}
|