Hi all,
for the code shown below , every thing is okey except few things i output the obj[i](sure the [] is overloaded) with the overloaded << but inside the operator definition i was outputing the m data member of the reference object,how ever it also outputs the m data member of obj[i] with the right data , i really wasn't expecting that i thought it will give me an error but how it gives me the correct behavior even the implementation of the function associated with m private varible and not n[inedx]
cout<<obj //give correct answer
cout<<obj[i] //how it give the correct answer?
////////////program code/////////////////
#include<iostream>
#include <cassert>
using namespace std;
class test{
private:
int n[10];
int m;
public:
test(){
m = 0;
for (int i = 0; i < 10;i++)
n[i] = 0;
}
test(int k) :m(k){}
friend ostream&operator<<(ostream&, test&);
friend istream&operator>>(istream&, test&);
void operator++();
test operator++(int);
int&operator[](const int);
};
ostream&operator<<(ostream&out, test&c){
out << c.m;
return out;
}
istream&operator>>(istream&in, test&c){
in >> c.m;//in<<c.n;
return in;
}
void test::operator++(){
++m;
}
test test::operator++(int){
test temp(m);
++(*this);
return temp;
}
int& test ::operator[](const int index){
assert(index >= 0 && index < 10);
return n[index];
}
int main(){
test obj(10);
for (int i = 0; i < 10; i++) obj[i] = i*i;
for (int i = 0; i < 10; i++)
cout << obj[i] << " ";
cout << endl;
system("pause");
return 0;
}