mystring類的實現

2021-08-03 08:40:33 字數 1036 閱讀 2985

#ifndef _cmystring_h_

#define _cmystring_h_

#include

#include

class cmystring

_data = new

char[strlen(s) + 1];

strcpy(_data, s);

}//copy ctor

cmystring(const cmystring &other)

//dtor

~cmystring()

//assign operator

cmystring& operator=(const cmystring &other)

friend

std::ostream& operator

<<(std::ostream &os, const cmystring &s)

private:

char *_data;

};#endif

#include 

#include "mystring.h"

using

namespace

std;

int main(int argc, char *argv)

考慮賦值運算子中new會產生異常,為了寫出異常安全性的**,上面的**有兩種修改方案:

1. 先new,成功之後再delete掉,不成功則返回原來的狀態

2. 先產生乙個暫時的棧例項,然後交換兩者的資料成員(字元指標),當跳出作用域後,棧例項銷毀會銷毀原來的資料成員

方案1

cmystring& operator= (const cmystring& other)

方案2

cmystring& operator=(const cmystring &other)

string類的實現(mystring)

最近參加了實習招聘感覺自己的c 都快忘光了,其中面試過程中問到了string類的實現,需手寫實現一遍。現在再實現一下 class mystring inline mystring mystring char str null else inline mystring mystring inline ...

C 之實現MyString類

1.mystring.h pragma once include using namespace std class mystring 2.mystring.cpp include mystring.h 建構函式 mystring mystring const char str else 拷貝建構函...

MyString類的實現 基礎中的基礎C語言

mystring 類是學習 c 的過程中乙個很重要的例子,涉及到物件導向的封裝 堆記憶體申請和釋放 函式的過載以及 c 的 big three 本例子重點在於複習和理解上述的 c 特性,實現的功能並不多。mystring 的宣告中包含了乙個帶指標的 c 類應有的函式,並且包含了一些常用的功能。其中終...