现在的位置: 首页 > 综合 > 正文

String

2014年02月06日 ⁄ 综合 ⁄ 共 849字 ⁄ 字号 评论关闭
class myString
{
private:
	char* _ptext;
	int _length;

public:
	
	myString(char* text, int length)
	{
		memcpy(_ptext, text, length);
	}

	static myString* New_myString(char* text, int length)
	{
		return new(length) myString(text, length);
	}

	void show()
	{
		printf("%s\n", _ptext);
	}

	void* operator new(size_t cb, int length)
	{
		void* p = malloc(cb+length);
		((myString*)p)->_ptext = (char*)p + cb;// error for (char*)(p+cb), because void*
		((myString*)p)->_length = length;
		return p;
	}

	void operator delete(void* p, int length) // this is just only to compare with new operator in order to avoid warning.
	{
		free(p);
	}

	void operator delete(void* p) // delete calls this function actually
	{
		free(p);
	}

};

/*
myString: |--_ptext--|--_length--|**********text memory**********|
          |<-----------malloc(sizeof(myString)+length----------->|
*/

int _tmain(int argc, _TCHAR* argv[])
{
    myString* str = new(6) myString("hello", 6);//myString::New_myString("hello",6);
    str->show();
    delete str;
}





抱歉!评论已关闭.