懒码农。。。。。。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

转自: http://blog.csdn.net/csdnxw/archive/2005/10/07/496633.aspx

 

 

//StudentScore结构和其自定义操作符都是为了演示该功能而编写的,并没有实际意义

#include <iostream>

#include <tchar.h>

#include "windows.h"

//学生成绩结构体

struct StudentScore

{

    int iStuID;

    int iCourseID;

    int iScore;

     //自定义==操作符

    bool operator==(StudentScore &oResID2)

    {

        return (iStuID == oResID2.iStuID) && (iCourseID == oResID2.iCourseID) && (iScore == oResID2.iScore);

    };

     //自定义!=操作符

    bool operator!=(StudentScore &oResID2)

    {

        return !operator==(oResID2);

    };

     //自定义=操作符

     //函数定义成了void类型,程序可以编译通过,如果不需要操作符的返回值(如==操作符),这样定义也可以。

    void operator = (StudentScore &oResID2)

    {

         //iStuID表示调用"="操作符时,"="左边的那个结构体对象的iStuID,其他同

        iStuID = oResID2.iStuID;

        iCourseID = oResID2.iCourseID;

        iScore = oResID2.iScore;

    };

     //自定义+操作符

    void operator + (StudentScore &oResID2)

    {

        iStuID += oResID2.iStuID;

        iCourseID += oResID2.iCourseID;

        iScore += oResID2.iScore;

    };

     //自定义+=操作符

    void operator+=(StudentScore &oResID2)

    {

        iStuID += oResID2.iStuID;

        iCourseID += oResID2.iCourseID;

        iScore += oResID2.iScore;

    };

};

//打印学生成绩

void PrintStudentScore(StudentScore &oResID)

{

    printf("iStuID: %d, iCourseID: %d, iScore: %d\n", oResID.iStuID, oResID.iCourseID, oResID.iScore);

}

/*

//这么声明也可以,只是得把两个操作数都写出来。

bool operator==(StudentScore &oResID1, StudentScore &oResID2)

{

    return (oResID1.iStuID == oResID2.iStuID) && (oResID1.iCourseID == oResID2.iCourseID) && (oResID1.iScore == oResID2.iScore);

};

*/

//主函数,演示结构体自定义操作符的使用

int _tmain(int argc, _TCHAR* argv[])

{

    StudentScore ResID1 = {1, 2, 3};

    StudentScore ResID2 = {1, 2 ,3};

     //使用==操作符

    if(ResID1 == ResID2)

    {

        //MessageBox(NULL, "The Same!", "Compare", MB_OK);

        printf("The Same!\n");

    }

    ResID2.iScore = 4;

     //使用!=操作符

    if(ResID1 != ResID2)

    {

        //MessageBox(NULL, "NOT The Same!", "Compare", MB_OK);

        printf("NOT The Same!\n");

    }

     //使用=操作符

    StudentScore ResID3 = ResID1;// + ResID2;

    PrintStudentScore(ResID3);

     //使用+=操作符

    ResID3 += ResID3;

    PrintStudentScore(ResID3);

    return 0;

}

//程序使用VS.net编译通过,执行结果如下

/*

The Same!

NOT The Same!

iStuID: 1, iCourseID: 2, iScore: 3

iStuID: 2, iCourseID: 4, iScore: 6

*/ 

posted on 2010-07-21 15:38  阿彬  阅读(2097)  评论(0编辑  收藏  举报