需要實現:構造函數, 拷貝構造函數,複製運算符,析構函數,size函數等等。
主要思路:用cstring的一些庫函數來實現。
底層的數據結構char*
會用到 strlen, strcpy等庫函數
#include <iostream>
#include <string>
#include <vector>
#include<cmath>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
class String{
public:
String();
String(const String & str);
String(const char* str);
String& operator=(String str);
char* c_str() const;
~String();
int size() const;
private:
char* data;
};
int String::size() const {
return strlen(data);
}
String::~String() {
delete [] data;
}
char* String::c_str() const {
return data;
}
String::String():data(new char[1]) {
*data='\0';
}
String& String::operator=(String str) {
data=new char[str.size()+1];
strcpy(data,str.c_str());
return *this;
}
String::String(const String& str) : data(new char[str.size()+1]) {
strcpy(data, str.c_str());
}
String::String(const char* str) : data(new char[strlen(str)+1]) {
strcpy(data,str);
}
// 以下代碼用來測試
void foo(String x)
{
}
void bar(const String& x)
{
}
String baz()
{
String ret("world");
return ret;
}
int main()
{
String s0;
String s1("hello");
String s2(s0);
String s3 = s1;
s2 = s1;
foo(s1);
bar(s1);
foo("temporary");
bar("temporary");
String s4 = baz();
std::vector<String> svec;
svec.push_back(s0);
svec.push_back(s1);
svec.push_back(baz());
svec.push_back("good job");
system("pause");
return 0;
}