1 案例:+ ,- ,++, --


// 操作符重载.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


class Fraction
{
public:
Fraction(): num(2),den(1){
//默认值
}

Fraction(int n,int d):num(n),den(d){

}

~Fraction();


Fraction operator + (const Fraction &other){
Fraction result;
result.den = den * other.den;//分母相乘
result.num = num * other.den + den * other.num;//分子交叉相乘
return result;
}



Fraction operator - (const Fraction &other){
Fraction result;
result.den = den * other.den;//分母相乘
result.num = num * other.den - den * other.num;//分子交叉相减
return result;
}

Fraction operator ++ (){
Fraction result;
result.den = den ;//分母不变
result.num = num + den;//分子加上分母
return result;
}

Fraction operator -- (){
Fraction result;
result.den = den ;//分母不变
result.num = num - den;//分子减去分母
return result;
}

public:
int num;
int den;

};

Fraction::~Fraction()
{

}


int _tmain(int argc, _TCHAR* argv[])
{
Fraction *f1 = new Fraction(5,6);
Fraction f2(2,3);
Fraction f3(3,5);
Fraction f4 = f2 + f3;
Fraction f5 = f2 - f3;
Fraction f6 = f5--;
Fraction f7 = f5++;

return 0;
}



2 案例: []

 1 简要说明: 

   创建2个类,Student和StudentData类,

   Student里有id,

   StudentData里使用操作符[]获取Student,然后输出id

  2 代码如下:

   

// 重载2.cpp : 定义控制台应用程序的入口点。
// [] 重载案例

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>


class Student
{
public:
Student(){}
Student(int id):id(id){}

~Student(){}

void showId(){
printf("student id:%d\n",id);
}

private:
int id;
};


class StudentData
{
public:
StudentData(int size);
~StudentData();

void addStudent(Student *stu){
*(_stu_buf + count ) = *stu;
count++;
}

Student operator[] (int id){
return _stu_buf[id];
}
private:
int count;
Student *_stu_buf;
};

StudentData::StudentData(int size)
{
count = 0;
_stu_buf = (Student *)malloc(size * sizeof(Student));
}

StudentData::~StudentData()
{

}


int _tmain(int argc, _TCHAR* argv[])
{
//定义student集合
StudentData data(10);

//批量创建student
for (int i = 0; i < 10; i++)
{
Student stu(i);
data.addStudent(&stu);
}

for (int i = 0; i < 10; i++)
{
// 显示id
data[i].showId();
}


while (true)
{

}

return 0;
}


     3 效果如下

C/C++: 操作符重载案例_+-++--