// String.h
#ifndef STRING_H
#define STRING_H
#include <exception>
template <class T>
class String {
T *pData;
unsigned elementNum;
public:
String() { pData = 0; elementNum = 0; }
String(const String &S) { pData = 0; *this = S; }
~String() { delete[] pData; }
String concat(const String &S);
void insert(unsigned Position, const T &Element);
const T &operator[](unsigned Pos) const;
String &operator=(const String &S);
};
template<class T>
String<T> String<T>::concat(const String &S) {
String RetVal;
if ((RetVal.elementNum = elementNum + S.elementNum) == 0) {
RetVal.pData = 0;
} else {
RetVal.pData = new T[RetVal.elementNum];
for (unsigned i = 0; i < RetVal.elementNum; i++) {
RetVal.pData[i] = (i < elementNum) ? pData[i] : S.pData[i - elementNum];
}
}
return RetVal;
}
template<class T>
void String<T>::insert(unsigned Position, const T &Element) {
unsigned NewSize = (Position < elementNum) ? (elementNum + 1) : (Position + 1);
T *pTemp = new T[NewSize];
for (unsigned i = 0, j = 0; j < NewSize; i++, j++) {
if (j == Position) {
i--;
} else {
pTemp[j] = (i < elementNum) ? pData[i] : 0;
}
}
pTemp[Position] = Element;
delete[] pData;
pData = pTemp;
elementNum = NewSize;
}
template<class T>
const T &String<T>::operator[](unsigned Pos) const {
if (Pos >= elementNum) {
throw std::exception("Hibas index!");
}
return pData[Pos];
}
template<class T>
String<T> &String<T>::operator=(const String<T> &S) {
if (this == &S) {
return *this;
}
delete[] pData;
if ((elementNum = S.elementNum) == 0) {
pData = 0;
} else {
pData = new T[elementNum];
for (unsigned i = 0; i < elementNum; i++) {
pData[i] = S.pData[i];
}
}
return *this;
}
#endif // STRING_H
// Main.cpp
#include <iostream>
using namespace std;
#include "String.h"
int main() {
try {
String<char> s1;
s1.insert(0, 'A');
s1.insert(0, 'B');
s1.insert(10, '0');
s1.insert(0, 'C');
String<char> s2 = s1;
cout << s2[2] << endl;
cout << s2[1000] << endl; // itt kivételt dob
} catch (...) {
cerr << "Hiba!" << endl;
}
return 0;
}
// Követelmények a tárolandó típussal szemben:
// - rendelkezik alapértelmezett konstruktorral
// - az értékadó (=) operátor helyesen használható vele