运算符重载

本文详细介绍了C++中单目运算符和二元运算符的重载,通过具体代码实例展示了如何在类中实现运算符重载,并将其应用于不同数据类型的操作。同时,还探讨了类成员函数返回值操作类型的不同情况。

1.C++提供了单目运算符和二元运算符的重载,这样可方便同类成员函数对不同数据类型的操作,返回值操作类型也可能不同,

View Code
//add.hpp
#ifndef _HHADD
#define _HHADD
class add
{
public:
  int temp;
  //int b;
  add()
  {
  temp=0;
  }
};
#endif
//addHPP.hpp
#include "add.hpp"
add operator+(add inputfi, int b)
{
return add(inputfi.temp+b);
};
//main.cpp
#include "add.hpp"
#include "addFUN.hpp"
#include <iostream>
using namespace std;
int main()
{
add output1(3),sum;
//sum.b=output1.operator+(output2);
sum=output1+8;
cout<<"the sum of the results"<<sum.temp<<endl;
return 0;

}
 1 class A
 2 {
 3 public:
 4  int a;
 5  int b;
 6  int c;
 7  A(): a(0), b(0),c(0)
 8 {}//default constructor
 9  A(int d, int e, int f):a(d),b(e),c(f)
10 {}//chongzai constructor
11 };
12 A operator+(const A &ori)
13 {
14 a=a+ori.a;
15 b=b+ori.b;
16 c=c+ori.c;
17 return *this;
18 }
19 };
20 int main()
21 {
22 A, output1,output2(10,20,30);
23 output1+=output2;
24 cout<<output1.a<<output1.b<<output1.c<<endl;
25 return 0;
26 }

 

转载于:https://www.cnblogs.com/xiaofuzheng/archive/2012/08/27/2659237.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值