【C++ 自写String】

发布时间:2024年01月24日

CString.hpp

#include <iostream>
#include <string.h>

#pragma warning(disable:4996)
using namespace std;

class CString {
private:
	int len;
	char* data;

public:
	CString():data(nullptr),len(0) {
		cout << "0空构造\n";
	}

	CString(const char* _data) 
	{
		if (!_data) {
			len = 0;
			data = new char(1);
			*data = '\0';
			cout << "1空构造\n";
		}
		else {
			len = (int)strlen(_data);
			data = new char[strlen(_data) + 1];
			memset(data, 0, len + 1);
			strcpy(data, _data);
			cout << "char*构造\n";
		}
		
	}
	const char* getValue() const {
		return data;
	}

	int getLength() const{
		return len;
	}

	CString (const CString& str)
	{
		len = str.getLength();
		data = new char[len+1];
		memset(data, 0, len + 1);
		strcpy(data, str.getValue());
		cout << "str构造\n";
	}

	CString& operator=(const CString & str)
	{
		if (this == &str) {
			return *this;
		}
		len = str.getLength();
		delete[] data;
		data = new char[len + 1];
		strcpy(data, str.getValue());
		return *this;
	}

	CString operator+(const CString &str) const
	{
			CString nstr;
			nstr.len = this->len + str.getLength();
			nstr.data = new char[nstr.len + 1];
			strcpy(nstr.data, (*this).data);
			strcat(nstr.data, str.getValue());
			return nstr;
	}

	~CString() {
		delete[] data;
	}
	

};



class String {
private:
	char* data; // 存储字符数组的指针
public:
	String(const char* str = "") : data(new char[strlen(str) + 1]) {
		strcpy(data, str);
	}

	~String() {
		delete[] data;
	}

	const char* getData() const {
		return data;
	}
};

Shape.hpp

#include<iostream>


class Shape {
public:
	virtual double printArea() = 0;
};

class Circle :public Shape {
private:
	double r;
public:
	Circle(double _r) { r = _r; }
	virtual double printArea() {
		return r * r * 3.14159;
	}
};

class Rectangle :public Shape {
private:
	double w, h;
public:
	Rectangle(double _w, double _h) { w = _w; h = _h; }
	virtual double printArea() {
		return w * h;
	}
};

class Triangle :public Shape {
private:
	double w, h;
public:
	Triangle(double _w, double _h)
	{
		w = _w;
		h = _h;
	}
	virtual double printArea() {
		return w * h /2;
	}
};

cmain.cpp

#include "CString.hpp"
#include "Shape.hpp"
#include <vector>

int main() 
{
#if 1
	CString s1("123");
	CString s2(s1);
	CString s3 = s1 + s2;
	CString s4;
	s4 = s3;
	cout << s4.getLength() << "," << s4.getValue() << endl;

	vector<Shape*> ss;
	Shape* c = new Circle(2.1);
	Shape* r = new Rectangle(4, 5);
	Shape* t = new Triangle(4,2);
	ss.push_back(c);
	ss.push_back(r);
	ss.push_back(t);
	for (auto v = ss.begin(); v != ss.end(); v ++) {
		cout<< "area:" << (*v)->printArea() << endl;
		Shape* ptr = *v;
		delete ptr;
		ptr = nullptr;
	}
	ss.erase(ss.begin(), ss.end());
#endif
	return 0;
}

在这里插入图片描述

文章来源:https://blog.csdn.net/weixin_45397344/article/details/135830736
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。