operator overloading in c++
Possible Duplicate:
Operator overloading
Hi guys can some one please suggest a good tutorial on operator overloading?
I was going through this code on operator overloading and I have the following doubts
code:
#include <iostream>
using namespace std;
class Array {
int *a;
int size;
int capacity;
public:
Array (int c) {a=new int[c]; size=0; capacity =c; } ;
Array & operator << (int x);
int operator [] (int i) {
if (i<size) return a[i] ;
else {
cout <<"Segmentation Fault Prevented!n";
return -1;
}
};
};
Array &Array::operator << (int x) {
if (size < capacity) a[size++] = x;
else {
int *tmp = new int[size+capacity];
for (int j=0; j<size; j++)
tmp[j]=a[j];
delete [] a;
a = tmp;
a[size++]=x;
capacity=size+capacity;
}
return *this;
} ;
int main (int agrc, char *argv[] ) {
Array b(10);
for (int i=0; i<100; i++) b << i;
b << 1 << 2 << 3;
for (int i=0; i<105; i++) cout << b[i] << endl;
}
I have these doubts:
Array & operator << (int x);
mean? int operator [] (int i)
- if this is a function why are we putting square brackets here? Array &Array::operator
means what? *this
? Please help me...I am new to c++ so have these doubts.... Thanks in advance
<<
operator []
operator, so you can use yourobject[something]
. It's used eg by std::map
Answer to (1): Did you look at the FAQ? http://www.parashift.com/c++-faq-lite/operator-overloading.html
Everytime you encount T operatorX
, where X
can be any of (),[],<<,>>,+,+=,=,--,++
etc., that's what is called "operator overloading". It does just what it says -- it enables you to use that operator on the class it's overloaded for. For example your array could be accessed like this:
Array myArr(10);
myArr[0] == 5;
myArr[1] == 10;
// ^^^ --- this is using the `operator[]` with an int parameter
链接地址: http://www.djcxy.com/p/12714.html
上一篇: 内部操作符与外部类重载
下一篇: 运算符在c ++中重载