string.h函數
#pragma once class string { public: string(const char* str = nullptr); string(const string& str); ~string(); string& operator=(const string& str); string& operator+=(const string& str); char& operator[](int n) const; char& operator[](int n); bool operator==(const string& str) const; int size() const; const char* c_str() const; bool empty() const; friend const string operator+(const string& lhs, const string& rhs); private: char *data; int length; };
string.cpp優化
#include "string.h" #include <string.h> #include <stdio.h> const string operator+(const string& lhs, const string& rhs) { string tmp(lhs); tmp += rhs; return tmp; } string::string(const char * str) { if (!str) { length = 0; data = new char[1]; *data = '\0'; } else { length = strlen(str); data = new char[length + 1]; strcpy(data, str); } printf("string constructor\n"); } string::string(const string & str) { length = str.size(); data = new char[length + 1]; strcpy(data, str.c_str()); printf("string copy constructor\n"); } string::~string() { length = 0; delete[] data; printf("string destructor\n"); } string& string::operator=(const string & str) { if (this == &str) return *this; delete[] data; length = str.size(); data = new char[length + 1]; strcpy(data, str.c_str()); return *this; } string & string::operator+=(const string & str) { length += str.size(); char *newdata = new char[length + 1]; strcpy(newdata, data); strcat(newdata, str.c_str()); delete[] data; data = newdata; return *this; } char& string::operator[](int n) const { return data[n]; } char& string::operator[](int n) { return data[n]; } bool string::operator==(const string & str) const { if (length != str.size()) return false; return strcmp(data, str.c_str()) ? false : true; } int string::size() const { return length; } const char * string::c_str() const { return data; } bool string::empty() const { return length == 0; }
main.cppthis
#include"string.h" int main() { char a[] = "hello", b[] = "world"; string s1(a), s2(b); string s3 = s1 + s2; return 0; }
string的+運算符重載進行了返回值優化,在Visual Studio Release模式下main函數中會調用兩次構造函數、一次複製構造函數、一次析構函數,比起不作優化減小了一次構造函數和一次析構函數spa
string constructor string constructor string copy constructor string destructor string destructor string destructor