C语言 自增运算符(前++后++)

C语言 自增运算符(前++后++)

一、简述

    了解自增运算符--前++后++ 的区别,以及又是如何实现的。(自减与自增类似)。

     

二、前++后++ 的区别

        无论前++,后++,最后都会自增1,区别在于是先自增,还是先参与运算。(自减与自增类似)。

        前++:先进行++操作。

        后++:后进行操作。

         

        测试代码:

#include <stdio.h>

int main(int argc, char *argv[])
{
	int i = 2, j = 2, a = 0, b = 0;
	
	a = ++i;
	b = j++;
	
	printf("a=%d\n", a);
	printf("b=%d\n", b);
	
	getchar();
	return 0;
}

       运行结果:

        

   反汇编代码(实现过程):

 

三、自减运算符

        前--:先进行--操作。

        后--:后进行操作。

        

        测试代码:

#include <stdio.h>

int main(int argc, char *argv[])
{
	int i = 2, j = 2, a = 0, b = 0;
	
	a = --i;
	b = j--;
	
	printf("a=%d\n", a);
	printf("b=%d\n", b);
	
	getchar();
	return 0;
}

       运行结果:

        

反汇编代码:

  

四、重载自增运算符(c++实现)

      实现思路:前++,直接对 变量加1,并返回+1后的结果;后++,先保存变量原来的值(要返回的),然后对变量+1,返回变量原来的值。

测试代码:

#include <iostream>

class Stu
{
public:
	int age;
	int id;
	void test();
	Stu& operator++();//重载Stu类的++运算符
	Stu operator++(int);
};

Stu& Stu::operator++()//前++
{	
	this->age = this->age + 1;
	return *this;
}

Stu Stu::operator++(int)//后++ (int是标记,区别前++)
{
	Stu save = *this;
	this->age = this->age + 1;
	return save;
}

int main(int argc, char *argv[])
{
	Stu s1 = {12,34}, s2 = {12,34};
	Stu s11, s22;

	s11 = ++s1;
	s22 = s2++;
	
	std::cout<<"s11.age="<<s11.age<<std::endl;
	std::cout<<"s22.age="<<s22.age<<std::endl;
	std::cin.get();

	return 0;
}

运行结果:

    从代码中可以看出,相对与前++,后++多了一步"保存"操作,即实现的指令增多,所以这样实现的前++比后++的效率要高。

猜你喜欢

转载自blog.csdn.net/nanfeibuyi/article/details/80834983