#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;
};