[原创]struct的自定义operator实例

//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

*/

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值