12.1 2 3
代码
//strngbad.h
#include <iostream>
#ifndef STRNGBAD_H_
#define STRNGBAD_H_
class StringBad
{
private:
//指针声明的字符串本身没有分配内存,在构造函数中使用new来分配内存
char * str;
//声明字符串长度
int len;
//无论创造多少个对象,程序只创造一个静态变量副本
//所有的对象共享一个静态变量
static int num_strings;
public:
StringBad(const char * s);
StringBad();
~StringBad();
friend std::ostream & operator<<(std::ostream & os,
const StringBad & st);
};
#endif // !STRNGBAD_H_
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include "12.1.h"
using namespace std;
//由StringBad类创造的对象都共享一个静态变量
//在类声明中声明,在定义类成员函数中初始化静态变量,除非是整型或枚举const
//声明描述了如何分配内存,但并不分配内存。
//初始化没有关键字static
int StringBad::num_strings = 0;
//在构造函数中分配内存
StringBad::StringBad(const char * s)
{
len = strlen(s);
//new给s分配内存,返回指针,赋值给str(类成员参数)
str = new char[len + 1];
strcpy(str, s);
//记录字符串数
num_strings++;
cout << num_strings << ": \"" << str
<< "\"object created\n";
}
StringBad::StringBad()
{
len = 4;
str = new char[4];
strcpy(str, "C++");
num_strings++;
cout << num_strings << ": \"" << str
<< "\" default object created\n";
}
//在析构函数中释放内存
//在构造函数中使用new[]分配内存,在析构函数中必须使用delete[]释放内存
StringBad::~StringBad()
{
cout << "\"" << str << "\" object deleted, ";
--num_strings;
cout << num_strings << " left\n";
//delete释放内存
delete[] str;
}
std::ostream & operator<<(std::ostream & os, const StringBad & st)
{
os << st.str;
return os;
}
//该程序的结果包含错误,这是一个不完美的类
#include <iostream>
#include "12.1.h"
using std::cout;
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 Bow1 for Dollars");
cout << "headline1: " << headline1 << endl;
cout << "headline2: " << headline2 << endl;
cout << "sports: " << sports << endl;
//通过引用传值
callme1(headline1);
cout << "headline1: " << headline1 << endl;
//由于callme2函数是值传递,导致错误
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()" << endl;
system("pause");
return 0;
}
void callme1(StringBad & rsb)
{
cout