64,654
社区成员
发帖
与我相关
我的任务
分享
#ifndef TEMPLATE_STRING
#define TEMPLATE_STRING
template<class C> class String
{
struct Srep;
Srep* rep_;
public:
String();
String(const C*);
String(const String&);
String& operator=(const C*);
String& operator=(const String&);
~String();
class Range {};
void check(int)const;
C read(int)const;
void write(int, C);
C operator[](int)const;
int size()const;
String& operator+=(const String&);
String& operator+=(const C*);
public:
struct Srep {
C* s_;
int sz_;
int n_;
Srep(int, const C*);
~Srep();
Srep* get_own_copy();
void assign(int, const C*);
private:
Srep(const Srep&);
Srep& operator=(const Srep&);
};
};
#endif // !TEMPLATE_STRING
#include "stdafx.h"
#include "String.h"
template<class C> String<C>::Srep::Srep(int nsz, const C* p) {
n_ = 1;
sz_ = nsz;
s_ = new C[sz_ + 1];
memcpy_s(s_, sz_, p, nsz);
}
template<class C> String<C>::Srep::~Srep() {
delete[] s_;
}
template<class C> typename String<C>::Srep* String<C>::Srep::get_own_copy() {
if (n_ == 1)
return this;
n_--;
return new Srep(sz_, s_);
}
template<class C> void String<C>::Srep::assign(int nsz, const C* p) {
if (sz_ != nsz) {
delete[] s_;
sz_ = nsz;
s_ = new C[sz_ + 1];
}
memcpy_s(s_, sz_, p, nsz);
}
template<class C> String<C>::String() {
rep_ = new Srep(0, "");
}
template<class C> String<C>::String(const C* p) {
rep_ = new Srep(strlen(p), p);
}
template<class C> String<C>::String(const String& x) {
x.rep_->n_++;
rep_ = x.rep_;
}
template<class C> String<C>& String<C>::operator=(const C* p) {
if (rep_->n_ == 1) {
rep_->assign(strlen(p), p);
}
else {
rep_->n_--;
rep_ = new Srep(strlen(p), p);
}
return *this;
}
template<class C> String<C>& String<C>::operator=(const String& x) {
x.rep_->n_++;
if (--rep_->n_ == 0) {
delete rep_;
}
rep_ = x.rep_;
return *this;
}
template<class C> String<C>::~String() {
if (--rep_->n_ == 0) {
delete rep_;
}
}
template<class C> void String<C>::check(int i)const {
if (i < 0 || rep_->sz_ <= i) {
throw Range();
}
}
template<class C> C String<C>::read(int i)const {
return rep_->s_[i];
}
template<class C> void String<C>::write(int i, C c) {
rep_ = rep_->get_own_copy();
rep_->s_[i] = c;
}
template<class C> C String<C>::operator[](int i)const {
check(i);
return rep_->s_[i];
}
template<class C> int String<C>::size()const {
return rep_->sz_;
}
template<class C> String<C>& String<C>::operator+=(const String<C>& str) {
strcat_s(rep_->s_, strlen(str.rep_->s_), str.rep_->s_);
rep_->sz_ += strlen(str.rep_->s_);
return *this;
}
template<class C> String<C>& String<C>::operator+=(const C* p) {
int size = strlen(rep_->s_) + strlen(p) + 1;
C* cp = new C[size];
strncpy_s(cp, size, rep_->s_, strlen(rep_->s_));
strncat_s(cp, size, p, strlen(p));
rep_->assign(strlen(cp), cp);
return *this
}
#include "stdafx.h"
#include "String.h"
#include "string"
#include <iostream>
int main() {
std::string s = "abcd";
String<char> ms(s.c_str());
std::cout << "no error" << std::endl;
}