c++ 自加或自减 的运算符重载

#include<iostream>

using namespace std;

class CDemo{
	private:
		int n;
	public:
		CDemo(int i=0):n(i){}
		CDemo operator++();//  ++d  成员函数 
		CDemo operator++(int);// d== 
		operator int(){  return n;}///强制类型转换 
	    int get_n(){
	    	return n;
		}
		friend CDemo operator--(CDemo &t);// 全局函数
		friend CDemo operator--( CDemo &t,int );
};
CDemo CDemo::operator++(){
	n++;
	return *this;
}
CDemo CDemo::operator++(int){
	CDemo tmp(*this);
	n++;
	return tmp;
}

CDemo operator--( CDemo &d )
{
	d.n--;
	return d;
}

CDemo operator--( CDemo &d, int )
{
     CDemo temp(d);
	 d.n--;
	 return temp;	
} 

int main(){
	CDemo d(5);
	cout<<(d--)<<endl; 
	d++;
	cout<<(++d)<<endl;
	++d;
	return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言中的运算符重载是指对已有的运算符重新定义其操作行为。然而,C语言并不支持运算符重载的概念。在C语言中,我们不能直接通过重载运算符来定义自定义类型的运算。相反,我们需要使用函数来实现运算符的功能。 如果您想要对自定义类型进行运算,您可以通过定义相应的函数来实现。例如,如果您有一个自定义的结构体类型,您可以为该结构体定义一个法函数和一个法函数来实现运算。 下面是一个示例代码,演示如何在C语言中实现自定义类型的运算: ```c #include <stdio.h> // 自定义结构体类型 typedef struct { int x; int y; } Point; // 法函数 Point add(Point p1, Point p2) { Point result; result.x = p1.x + p2.x; result.y = p1.y + p2.y; return result; } // 法函数 Point subtract(Point p1, Point p2) { Point result; result.x = p1.x - p2.x; result.y = p1.y - p2.y; return result; } int main() { Point p1 = {2, 3}; Point p2 = {4, 5}; // 调用法函数 Point sum = add(p1, p2); printf("Sum: %d, %d\n", sum.x, sum.y); // 调用法函数 Point diff = subtract(p1, p2); printf("Difference: %d, %d\n", diff.x, diff.y); return 0; } ``` 在上面的代码中,我们定义了一个名为`Point`的自定义结构体类型,并为它定义了一个法函数`add`和一个法函数`subtract`。通过调用这些函数,我们可以对`Point`类型的变量进行运算。 因此,在C语言中,我们不能直接进行运算符重载来实现运算,但可以通过定义函数来实现相同的操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值