#C++PrimerPlus# Chapter12_Exersice1&2&3_stringbad
定义一个不完善的类,感受特殊成员函数在默认定义下给程序带来的错误和隐患。
StringBad类
私有部分:1,char* 一个指向字符串起点的指针;
2,int 字符串的长度(不含\0);
3,静态类成员变量 static int 用于记录类对象的总数;
公有部分:1,构造和析构函数;
2,友元函数 重载“<<"运算符 实现字符串的输出。
程序清单如下:
// strngbad.h
#ifndef STRNGBAD_H_
#define STRNGBAD_H_
#include <iostream>
class StringBad
{
private:
char* str;
int len;
static int strNum;
public:
StringBad();
StringBad(const char* s);
~StringBad();
friend std::ostream& operator<<(std::ostream& os, const StringBad& st);
};
#endif
// strngbad.cpp
#include "strngbad.h"
#include <cstring>
int StringBad::strNum = 0; // 静态类成员变量的初始化不在类声明中 类声明只描述如何分配内存 但不分配内存
StringBad::StringBad()
{
len = 4;
//str = new char[4];
//std::strcpy(str, "C++");
str = new char[1];
str[0] = '\0';
strNum++;
std::cout << strNum << ": \"" << str << "\" object created\n";
}
StringBad::StringBad(const char* s)
{
len = strlen(s);
str = new char[len + 1];
strcpy_s(str,len+1, s);
strNum++;
std::cout << strNum << ": \"" << str << "\" default object created\n";
}
StringBad::~StringBad()
{
delete [] str;
--strNum;
std::cout << "\"" << str << "\" object deleted, " << strNum << " left\n";
}
std::ostream& operator<<(std::ostream& os, const StringBad& st)
{
os << st.str;
return os;
}
// vegnews.cpp
#include "strngbad.h"
void callme1(StringBad& rsb);
void callme2(StringBad s);
int main()
{
using std::cout;
using std::endl;
{
cout << "Staring 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";
system("pause>nul");
return 0;
}
void callme1(StringBad& rsb)
{
std::cout << "String passed by reference:\n";
std::cout << " \"" << rsb << "\"\n";
}
void callme2(StringBad sb)
{
std::cout << "String passed by value:\n";
std::cout << " \"" << sb << "\"\n";
}
结束。
结果:程序出错中断。
原因:函数callme2时按值传递的,隐式的复制了一个临时对象,临时对象逐个成员按值复制实参对象,包括指针成员。按值复制指针时直接复制指针指向的地址,不会生成所指内容的副本,也就是说所指部分同时被两个指针所指向。当临时对象结束寿命时将调用析构函数,析构函数将释放临时对象指针成员所指内容所占用的内存。但此刻实参对象指针成员仍然指向此已被释放的内存地址,故而引发错误。其余错误是上述错误同种原因的不同表现形式,不再赘述。