C++重载【】

#include<stdio.h>
#include<string.h>

class Text
{
public:
	int m_size;
	char* m_buf;
	Text(const char* str)
	{
		m_size = strlen(str) + 1;
		m_buf = new char[m_size];
		strcpy(m_buf, str);
	}
	Text()
	{
		delete[] m_buf;
	}
	char& operator[] (int index) //按照index重载[]
	{
		return m_buf[index];
	}
};

int main()
{
	Text t1("helloworld");
	char ch = t1[0];
	t1[0] = 'H';
	return 0;
}

第二个例子

main.cpp


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "DataStore.h"
int main()
{
	DataStore ds;

	Student s1 = { 201501, "shaofa" };
	ds.Add(&s1);

	Student s2 = { 201502, "AnXin" };
	ds.Add(&s2);

	ds.Print();

	Student& st = ds["shaofa1"];
	puts(st.name);
	if (st.id > 0)
	{

	}

	Student& ttt = ds[201502];
	puts(ttt.name);
	if (ttt.id > 0)
	{

	}
	return 0;
}


DataStore.cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "DataStore.h"

Student DataStore::null_one = {-1, "null"};

DataStore::DataStore()
{
	m_head.next = NULL;
}

DataStore::~DataStore()
{
	Student* p = m_head.next;
	while(p)
	{
		Student* next = p->next;
		free(p);
		p = next;
	}
}

Student&  DataStore::operator [] (const char* name)
{
	Student* p = m_head.next; 
	while(p)
	{
		if(strcmp(p->name, name) == 0)
		{
			return *p;
		}

		p = p->next; // 下一个对象
	}
	//return NULL;
	return null_one;
}

Student& DataStore::operator [] (int id)
{
	Student* p = m_head.next; 
	while(p)
	{
		if(p->id == id)
		{
			return *p;
		}

		p = p->next; // 下一个对象
	}
	return null_one;
}

void DataStore::Add(const Student* data)
{
	// 创建对象、复制数据
	Student* copy = (Student*)malloc(sizeof(Student));
	*copy = *data;

	// 插入一个对象到链表中
	Student* cur = m_head.next; // 当前节点current
	Student* pre = &m_head;  // 上一个节点previous
	while(cur)
	{		
		if(copy->id < cur->id) // 找到这个位置
			break;

		pre = cur;
		cur = cur->next;  // 找到最后一个对象
	}

	// 插入到pre节点的后面
	copy->next = pre->next;
	pre->next = copy;
}

Student* DataStore::Find(int id)
{
	Student* p = m_head.next; 
	while(p)
	{
		if(p->id == id)
			return p;

		p = p->next; // 下一个对象
	}
	return NULL;
}

void DataStore::Print()
{
	Student* p = this->m_head.next; 
	while(p)
	{
		printf("ID: %d, name: %s\n", p->id, p->name);
		p = p->next; // 下一个对象
	}
}

 


DataStore.h

struct Student
{
	int id;
	char name[16];
	Student* next;
};

class DataStore
{
public:
	DataStore();
	~DataStore();

	Student& operator [] (const char* name);

	Student& operator [] (int id);

public:
	void Add(const Student* data);
	Student* Find(int id);
	void Print();

public:
	static Student null_one;

private:
	Student m_head;

};

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值