473,396 Members | 1,864 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

HOW overloaded operator eg [],(),->

sanjay123456
125 100+
Dear firiends ,
tell me that HOW overloaded operator eg [],(),->
how can i overloaded those operator

sanjay
Dec 25 '06 #1
6 1824
Dear firiends ,
tell me that HOW overloaded operator eg [],(),->
how can i overloaded those operator

sanjay
i would like to know the answer to this question two
does anyone knows a solution?
Dec 26 '06 #2
macklin01
145 100+
i would like to know the answer to this question two
does anyone knows a solution?
You need to add something like

Expand|Select|Wrap|Line Numbers
  1. double* operator()( int i, int j );
  2.  
to your class. (Replace double* with whatever you deem appropriate for the class.) For instance, I use the operator() as follows in my EasyBMP code:

Expand|Select|Wrap|Line Numbers
  1. BMP
  2. {
  3.  private:
  4.   RGBApixel** Pixels;
  5.   // ... more stuff
  6.  public:
  7.   RGBApixel* operator()(int i, int j);
  8.   // ... more stuff
  9. };
  10.  
  11. RGBApixel* BMP::operator()( int i, int j)
  12. { return &( Pixels[i][j] ); }
  13.  
In use, it works like this:
Expand|Select|Wrap|Line Numbers
  1. BMP SomeImage;
  2. SomeImage.ReadFromFile( "blah.bmp" );
  3.  
  4. cout << "pixel (3,2): (" 
  5.      << (int) SomeImage(3,2)->Red   << ","
  6.      << (int) SomeImage(3,2)->Green << ","
  7.      << (int) SomeImage(3,2)->Blue  << ")" << endl;
  8.  
I hope that helps point you in the right direction. -- Paul
Dec 26 '06 #3
horace1
1,510 Expert 1GB
Dear firiends ,
tell me that HOW overloaded operator eg [],(),->
how can i overloaded those operator

sanjay
below is some sample code from a 2D matrix class I implemented years ago
Expand|Select|Wrap|Line Numbers
  1. // Matrix class
  2. // uses an array of pointers p_rows which contains the start address of each row 
  3. //  in stored the array p_matrix, i.e. the address of element [row][column] is
  4. //      p_rows[row] + column      
  5. class Matrix                                               // define type Matrix
  6.       { // private members
  7.            string name;                                           // name of array
  8.            float *p_matrix;          // pointer to array of float to hold matrix
  9.            float **p_rows;                         // pointer to rows in p_array
  10.            int columns, rows;                   // size of matrix(rows, columns)
  11.         // member function, return reference to array element (row, column)
  12.            float & index(const int row, const int column) const
  13.               { return *(p_rows[row] + column); }
  14.  
  15. ...
  16.  
operator[] would be (no array bounds checking)
Expand|Select|Wrap|Line Numbers
  1.        // return pointer to array element indexed by ex_row, indexed from 1
  2.            float * operator[](const int ex_row) const
  3.                { return (p_rows[ex_row - 1] - 1); }
  4.  
operator() would be (throws exception on array index out of bounds)
Expand|Select|Wrap|Line Numbers
  1. // return reference to array element (ex_row, ex_col), indexed from 1         //
  2. //  throw exception if array index out of bo                                  //
  3. float & Matrix::operator()(int ex_row, int ex_col) const 
  4.     if ((ex_row < 1) || (ex_col < 1) || (ex_row > rows) || (ex_col > columns)) 
  5.        {
  6.         // error! create message for throwing exception
  7.         stringstream ss;
  8.         ss <<  " Matrix::operator() array " << name << 
  9.           "(" << ex_row  << "," << ex_col << ") out of bounds";
  10.         string s=ss.str();
  11.         throw out_of_range(s);       // out of bounds exception
  12.        }
  13.     return this->index(ex_row - 1, ex_col - 1);   // return reference to element 
  14. }
  15.  
full code is available from
http://www.geocities.com/horacespider/programming/C/matrix.txt
Dec 27 '06 #4
macklin01
145 100+
...
Exactly. :) Do note that if you make the function const, then your operator() will only be able to fetch the matrix value, but won't be able to change the matrix value. That's why I tend to not make it const when I write matrix libraries, so that you can use it in a way you'd use it on paper, e.g.,

*Matrix1(3,2) = *Matrix2(4,0);

A very simple 2D array class is included as part of the EasyBMP Extensions. (It doesn't actually rely upon EasyBMP.) It's fully open source, so you're free to look it over and use/abuse it as you see fit. :)

In the way the implementation is done, you can do things like this:
Expand|Select|Wrap|Line Numbers
  1. SimpleArray InputData;
  2. InputData.ReadFromFile( "PHI.dat" );
  3. SimpleArray OutputData( InputData.Rows, InputData.Cols );
  4. int i,j;
  5. for( i=0 ; i < InputData.Rows ; i++)
  6. {
  7.  for( j=0 ; j < InputData.Cols ; j++)
  8.  {
  9.   *OutputData(i,j) = pow( *InputData(i,j) , 2.0 ); 
  10.  }
  11. }
  12.  
Horace raised a good point about accessing data elements that are out of bounds. As he pointed out, you can check the bounds when you return the memory address. Another thing you can do, rather than throw and exception, is crop the index and give the user a warning. I do this with the operator() on my EasyBMP library. Here's an adaptation:
Expand|Select|Wrap|Line Numbers
  1. class Matrix
  2. {
  3.  private:
  4.   int Rows;
  5.   int Cols;
  6.   double** Data;
  7.   // ... etc
  8.  
  9.  public:
  10.   double* operator()( int i, int j );
  11.   // ... etc
  12. };
  13.  
  14. double* Matrix::operator()( int i, int j )
  15. {
  16.  if( i < 0 || i >= Rows )
  17.  { 
  18.   cout << "Matrix Warning: index " << i << " was out of bounds!" << endl
  19.        << "Cropping to range [0," << Rows-1 << "]" << endl;
  20.   if( i < 0 ){ i = 0; }
  21.   if( i >= Rows ){ i = Rows-1; }
  22.  }
  23.  if( j < 0 || j >= Cols )
  24.  { 
  25.   cout << "Matrix Warning: index " << j << " was out of bounds!" << endl
  26.        << "Cropping to range [0," << Cols-1 << "]" << endl;
  27.   if( j < 0 ){ j = 0; }
  28.   if( j >= Cols ){ j = Cols-1; }
  29.  }
  30.  return &( Data[i][j] );
  31. }
  32.  
Do note, however, that checks like these will slow the program down. If you know for certain that the programmer will only access correct matrix entries, you can cut those checks to speed up execution. -- Paul
Dec 27 '06 #5
horace1
1,510 Expert 1GB
macklin01 makes a good point about operator[] - in practice many functions need two versions one for 'normal' obects and one for constant objects,e.g in <vector>
http://www.cppreference.com/cppvector/vector_operators.html
shows
Expand|Select|Wrap|Line Numbers
  1. TYPE& operator[]( size_type index );
  2. const TYPE& operator[]( size_type index ) const;
  3.  
also the point about error checking is critical - the more you do the longer the execution time. e.g. in <vector> to access an element you can use at() or [] but
http://www.cppreference.com/cppvector/at.html
states "The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the vector."
Dec 27 '06 #6
horace1
1,510 Expert 1GB
macklin01 makes a good point about operator[] - in practice many functions need two versions one for 'normal' obects and one for constant objects,e.g in <vector>
http://www.cppreference.com/cppvector/vector_operators.html
shows
Expand|Select|Wrap|Line Numbers
  1. TYPE& operator[]( size_type index );
  2. const TYPE& operator[]( size_type index ) const;
  3.  
also the point about error checking is critical - the more you do the longer the execution time. e.g. in <vector> to access an element you can use at() or [] but
http://www.cppreference.com/cppvector/at.html
states "The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the vector.", i.e. [] does no array bounds checking.
Dec 27 '06 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Nitin Bhardwaj | last post by:
Thanx in advance for the response... I wanna enquire ( as it is asked many a times in Interviews that i face as an Engg PostGraduate ) about the overloading capability of the C++ Language. ...
5
by: Andy Jarrell | last post by:
I'm trying to inherit from a specific class that has an overloaded operator. The problem I'm getting is that certain overloaded operators don't seem to come with the inheritance. For example: ...
1
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen...
14
by: ambar.shome | last post by:
Hi, As you know there are few operators in C++ which cant be overloaded. They are: .., .*, ::, ?: , new , delete , sizeof , typeid , static_casr , dynamic_cast , const_cast ,...
1
by: Alex Zhitlenok | last post by:
Hi, My question is how to resolve in C# ambiguous overloaded operators? Let say, I have two unrelated classes A and B, each one implements overloaded operator + with the first parameter of type...
3
by: cybertof | last post by:
Hello, Is it possible in C# to have 2 overloaded functions with - same names - same parameters - different return type values If no, is it possible in another language ?
2
by: B. Williams | last post by:
I have an assignment for school to Overload the operators << and >and I have written the code, but I have a problem with the insertion string function. I can't get it to recognize the second of...
5
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason...
9
by: rohits123 | last post by:
I have an overload delete operator as below ////////////////////////////////// void operator delete(void* mem,int head_type) { mmHead local_Head = CPRMemory::GetMemoryHead(head_type);...
2
by: subramanian100in | last post by:
overloaded operator=() -------------------------------- overloaded assignment operator should be a non-static MEMBER function of a class. This ensures that the first operand is an lvalue. If...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.