برنامه ای به زبا سی پلاس پلاس برای بررسی عملگر افزایشی ++ و کاهشی -- بعد و قبل از یک متغیر
جمعه, ۱۶ مهر ۱۳۹۵، ۰۷:۲۵ ب.ظ
gameover.blog.ir
/* C++ program to demonstrate the working of ++ operator overlading. */
#include <iostream>
using namespace std;
class Check
{
private:
int i;
public:
Check(): i(0) { }
Check operator ++() /* Notice, return type Check*/
{
Check temp; /* Temporary object check created */
++i; /* i increased by 1. */
temp.i=i; /* i of object temp is given same value as i */
return temp; /* Returning object temp */
}
void Display()
{ cout<<"i="<<i<<endl; }
};
int main()
{
Check obj, obj1;
obj.Display();
obj1.Display();
obj1=++obj;
obj.Display();
obj1.Display();
return 0;
}
Output
i=0 i=0 i=1 i=1
Operator Overloading of Postfix Operator:
/* C++ program to demonstrate the working of ++ operator overlading. */
#include <iostream>
using namespace std;
class Check
{
private:
int i;
public:
Check(): i(0) { }
Check operator ++ ()
{
Check temp;
temp.i=++i;
return temp;
}
/* Notice int inside barcket which indicates postfix increment. */
Check operator ++ (int)
{
Check temp;
temp.i=i++;
return temp;
}
void Display()
{ cout<<"i="<<i<<endl; }
};
int main()
{
Check obj, obj1;
obj.Display();
obj1.Display();
obj1=++obj; /* Operator function is called then only value of obj is assigned to obj1. */
obj.Display();
obj1.Display();
obj1=obj++; /* Assigns value of obj to obj1++ then only operator function is called. */
obj.Display();
obj1.Display();
return 0;
}
Output
i=0 i=0 i=1 i=1 i=2 i=1
۹۵/۰۷/۱۶