首页 > 代码库 > C++实现SimpleString

C++实现SimpleString

摘自《C++编程思想》

/*
 * SimpleString.h
 *
 *  Created on: 2014年7月4日
 *      Author: Administrator
 */

#ifndef SIMPLESTRING_H_
#define SIMPLESTRING_H_

class SimpleString {
public:
	SimpleString();
	SimpleString(const char*);
	SimpleString(SimpleString&);
	virtual ~SimpleString();

	const char *string() const;
	SimpleString& operator=(const char*);
	SimpleString& operator=(const SimpleString&);

	void print_str();

private:
	char *_string;
	void duplicate(const char*);
};

#endif /* SIMPLESTRING_H_ */

/*
 * SimpleString.cpp
 *
 *  Created on: 2014年7月4日
 *      Author: Administrator
 */

using namespace std;

#include "SimpleString.h"
#include "string.h"
#include<iostream>

SimpleString::SimpleString() {
	// TODO Auto-generated constructor stub
	_string = 0;
}

SimpleString::SimpleString(const char *s) {
	// TODO Auto-generated constructor stub
	duplicate(s);
}

SimpleString::SimpleString(SimpleString &s) {
	// TODO Auto-generated constructor stub
	duplicate(s._string);
}

SimpleString::~SimpleString() {
	// TODO Auto-generated destructor stub
	delete[] _string;
}

void SimpleString::duplicate(const char *s) {
	if (s) {
		_string = new char[strlen(s) + 1];
		strcpy(_string, s);
	} else {
		_string = 0;
	}
}

SimpleString& SimpleString::operator =(const char *s) {
	char *pre_string = _string;
	duplicate(s);
	delete[] pre_string;
	return *this;
}

SimpleString& SimpleString::operator =(const SimpleString &s) {
	if (this == &s) {
		return *this;
	} else {
		return operator =(s._string);
	}
}

void SimpleString::print_str() {
	if (_string) {
		cout << _string << endl;
	} else {
		cout << "Warning: _string is null!" << endl;
	}
}

#include "SimpleString.h"

int main(int argc, char **argv) {
	SimpleString a;
	SimpleString b("hello world");
	SimpleString c(b);
	a.print_str();
	b.print_str();
	c.print_str();

	a = b;
	c = "you can do it!";
	a.print_str();
	b.print_str();
	c.print_str();

	return 0;
}

Warning: _string is null!
hello world
hello world
hello world
hello world
you can do it!