|
لغة
++C / Operator
overloading
|
ينقسم الoperator الى نوعين وهما
1-unary operator
2- Binary operators
والان هذه معظم ال operators التى يمكننا ان نجعلها overloaded
|
+
- * / = < > += - = *= /= << >> <<= >>= == != <
= > = ++ -- % & ^ ! |
~ &= ^= |=
&& || %=
[] ()
|
|
| لعمل overload لoperatorsنحتاج فقط الى كتابة كلمة operator يسبقها النوع ويليها الاشارةوبين قوسين المتغير كالأتى:
|
| (type operator sign (parameter
|
|
// vectors: overloading operators example
#include <iostream.h>
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x =
x + param.x;
temp.y = y + param.y;
return (temp);
}
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x
<< "," << c.y;
return 0;
}
|
|
| ويصبح البرنامج على شاشة السى كالأتى: |
|
المثال الثانى
|
| |
#include <iostream.h>
class CDummy {
public:
int isitme (CDummy& param);
};
int CDummy::isitme (CDummy& param)
{
if (¶m == this) return 1;
else return 0;
}
int main () {
CDummy a;
CDummy* b =
&a;
if (b->isitme(a) )
cout
<< "yes, &a is b";
return 0;
}
|
|
| ويظهر على شاشة السى كالأتى : |
|
|