Function () operator

Hey guys,

I am struggling to find my way out of this situation. I just want to call the [] operator within the () operator, which will be finally used/written on the screen with the ostream << operator. Whenever I'm using the sintax _elements[index] the execution crashes with the error vector out of range.

Do you have any ideea what should be the correct code ?


Header File:

typedef unsigned int Uint;
typedef vector<Uint> TVint;
typedef vector<Uint>::const_iterator Titerator;

class Sir
{
protected:
Uint _count;
TVint _elements;
public:
int index;
Sir():_count(0){}
Uint operator [] (int index);
Sir& operator() (int index);
virtual string Name() const=0;
virtual ~Sir(){}
virtual void CalculateValues(int index)=0;
protected:
friend ostream& operator<<(ostream &out, const Sir&sir);
};

CPP File:


ostream& operator<<( ostream &out, const Sir&sir)
{
for(Uint i=0;i<sir._count;++i)
{
out<<"................"<<endl;
out<<i<<"\t"<<sir._elemente[i]<<endl;
}
return out;
};


Uint Sir:: operator [] (int index)
{
if (index <0)
{
throw outofrange();
}
_count=index+1;
CalculateValues(index);
return _elements[_count];
}


Sir& Sir::operator() (int index)
{
_elements[index]; ?????????????????? - What is wrong with this expression ?
return *this;
}
Your operator() does not call your operator[], so whatever CalculateValues() does to validate the index is not happening.

To call the operator, call it by name:

1
2
3
4
5
Sir& Sir::operator() (int index)
{
operator[] (index);
return *this;
}

PS. Please use [code] tags.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Uint Sir:: operator [] (int index)
		{
			if (index <0)
			{
				throw outofrange();
			}
			_count=index+1;
			CalculateValues(index);
			return _elements[_count];
		}


		Sir& Sir::operator() (int index)
		{	
			operator[] (index);   [output]still not working[/output]
			return *this;
		}


		ostream& operator<<( ostream &out, const Sir&sir)
		{
		for(Uint i=0;i<sir._count;++i)
		{
		out<<"................"<<endl;
		out<<i<<"\t"<<sir._elements[i]<<endl;
		}
		return out;
		};



Still the same error when I try to execute ---- vector subscript out of range.


Is there any other way to call the operator [] with "index" as parameter ?

PS: CalculateValues(index) - validates the index within some range and
then push_back the elements in the vector.

Many thanks!
Topic archived. No new replies allowed.