C++ 类和动态内存分配(学习笔记)

C++ 类和动态内存分配(学习笔记)

示例代码(来自C++PrimerPlus)

文件中所有的英文的注释都是来自于书本的内容。

// string1.h -- fixed and augmented string class definition
// 这个文件用来描述一个自己定义的字符串类,.h 头文件中经常保存类、函数等的定义信息,
// 并在包含了该头文件的.cpp文件中得到实现。
#ifndef STRING1_H_
#define STRING1_H_
// 预编译过程中,如果发现程序定义过 STRING1_H_,
// 说明其中的内容已经被包含,重复包含同样的内容无法通过编译
// 所以通过 #ifndef #define #endif 确保中间的内容不会被重复引用。
#include <iostream>
using std::ostream;
using std::istream;
// 通过 using 引用的命名空间,特别指出要使用的名称而不是直接引用全部,
// 比如 std::ostream 而不是 std 在一些复杂的情况中很有帮助

class String
{
private:
	char* str;		// pointer to string
	int len;		// length of string
	// String 类中保存了字符串的首地址 str,并为其动态地分配内存空间
	// 当字符串内容改变时,长度(所占内存)随之改变,记录在 len 中,
	// 虽然 len 占据了空间,但能避免频繁的使用带来的每一次都要计算的开销。
	static int num_strings;	// number of objects
	static const int CINLIM = 80;	// cin input limit
	// static 关键字表明 num_strings 和 CIMLIM 两个 int 型变量是静态的。
	// 即不管今后创建了多少个 String 的对象,这两个变量只有一份,所有的 String 共用

public:
// constructors and other methods
	String(const char* s);	// constructor
	// 该构造函数同时可以作用于变量的类型转变,当需要一个 String 变量,
	// 而得到的输入是 char* 时,将通过这个构造函数自动的进行变量类型转换。
	String();				// default constructor
	// 没有任何形参的构造函数是默认构造函数,即使没有定义它,编译器也会自动生成
	// 但对于 String 类,如果是一个对象创建时使用的是自动生成的默认构造函数,它将不会通过 new 来动态的分配空间
	// 而在使用完毕调用析构函数时会使用 delete[] 关键字来释放 str 所占据的空间,这时会产生错误,因此必须要手动定义默认构造函数
	String(const String &);	// copy constructor
	// 复制构造函数如果没有被定义也会由编译器自动生成,但时常不会尽如人意,
	// 因为我们的 String 类有计数的功能,默认的复制构造函数不会增加它的数量统计
	~String();				// destructor
	int length() const { return len; }
// overloaded operator methods
	String & operator=(const String &);
	String & operator=(const char *);
	char & operator[](int i);
	const char& operator[](int i) const;
// overloaded operator friends
	friend bool operator<(const String& st, const String &st2);
	friend bool operator>(const String &st1, const String &st2);
	friend bool operator==(const String &st, const String &st2);
	friend ostream & operator<<(ostream & os, const String & st);
	friend istream & operator>>(istream & is, String & st);
	// 这里把返回值设置为 ostream 和 istream 而不是 void 是很有必要的
	// 比如使用 cout<< 时经常这样 cout<<1<<str<<endl; 这要求 cout << 1 运行后返回值仍然是  cout
// static int HowMany();
};
#endif
// string1.cpp -- String class methods
#include <cstring>		// string.h for some
#include "string1.h"	// includes <iostream>
using std::cin;
using std::cout;

// initializing static class member

int String::num_strings = 0;

// static method
int String::HowMany()
{
	return num_strings;
}

// class methods
String::String(const char * s)		// construct String from C string
{
	len = std::strlen(s);			// set size
	str = new char[len + 1]			// allot storage
	std::strcpy(str, s);			// initialize pointer
	num_string++;					// set object count
}

String::String()					// default constructor
{
	len = 4;
	str = new char[1];
	str[0] = '\0';					// default String
	num_string++;
}

String::String(const String & st)
{
	num_string++;				// handle static member update
	len = st.len;				// same length
	str = new char [len + 1];	// allot space
	std::strcpy(str, st.str);	// copy string to new location
}
// 复制构造函数,要求输入参数仍是本身的数据类型
// 在复制的时候采用复制字符串str里存储的所有字符的方式而不是单纯的复制这个指针
// 这种复制构造函数被称做深拷贝,如果只是复制了指针的地址的话,将会导致
// 几个保存了相同的字符串的 String,当其中一个被销毁时,字符串所占据的空间就已经被释放了,
// 如果其他几个 String 再释放空间就会产生问题
// 而且这也不符合面向对象的封装保护的思想。

String::~String()				// necessary destructor
{
	--num_strings;				// required
	delete [] str;				// required
}

// overloaded operator methods

	// assign a String to a String
String & String::operator=(const String & st)
{
	if (this == &st)
		return this;
	delete [] str;
	len st.len;
	str = new char[len + 1];
	std::strcpy(str, st.str);
	return *this;
}

	// assign a C string to a String
String & String::operator=(const char* s)
{
	delete [] str;
	len = std::strlen(s);
	str = new char[len + 1];
	std::strcpy(str, s);
	return *this;
}

	// read write char access for non_const String
char & String::operator[](int i)
{
	return  str[i];
}

	// read-only char access for const String 
const char & String::operator[](int i) const
{
	return str[i];
}

// overloaded operator friends

bool operator<(const String &st1, const String &st2)
{
	return (std::strcmp(st1.str, st2.str) < 0);
}

bool operator>(const String &st1, const String &st2)
{
	return st2 < st1;
}

bool operator==(cosnt String &st1, const String &st2)
{
	return (std::strcmp(st1.str, st2.str) == 0);
}

	// simple String output
ostream & operator<<(ostream & os, const String & st)
{
	os << st.str;
	return os;
}

	// quick and dirty String input
istream & operator>>(istream & is, String & st)
{
	char temp[String::CINLIM];
	is.get(temp, String::CINLIM];
	if (is)
		st = temp;
	while (is && is.get() != '\n')
		continue;
	return is;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值