473,806 Members | 2,771 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can we override [][] ?

I wanted to do an operator override for [][] but couldnt' figure out the
syntax. I tried this (code that doesn't compile commented out with //:

class CMyBitmap
{
public:
CMyBitmap( int Rows, int Columns ): Rows_( Rows ), Columns_( Columns )
{
Data_ = new SPixel[ Rows * Columns ];
}
~CMyBitmap()
{
delete[] Data_;
}

// error C2804: binary 'operator [' has too many parameters
// SPixel& operator[]( const int Row, const int Column )
// {
// return Data_[ Columns_ * Row + Column ];
// }

// error C2092: '[]' array element type cannot be function
// SPixel& operator[][]( const int Row, const int Column )

SPixel& Pixel( const int Row, const int Column )
{
return Data_[ Columns_ * Row + Column ];
}

private:
SPixel* Data_;
int Rows_;
int Columns_;

// No copy or assignment yet so disable by making private.
CMyBitmap ( CMyBitmap const& ) {};
CMyBitmap& operator=( CMyBitmap const& ) {};

};

Can we override 2d array access?
May 31 '06 #1
52 3502

"Jim Langston" <ta*******@rock etmail.com> wrote in message
news:KB******** *******@fe04.lg a...
I wanted to do an operator override for [][] but couldnt' figure out the
syntax. I tried this (code that doesn't compile commented out with //:

class CMyBitmap
{
public:
CMyBitmap( int Rows, int Columns ): Rows_( Rows ), Columns_( Columns )
{
Data_ = new SPixel[ Rows * Columns ];
}
~CMyBitmap()
{
delete[] Data_;
}

// error C2804: binary 'operator [' has too many parameters
// SPixel& operator[]( const int Row, const int Column )
// {
// return Data_[ Columns_ * Row + Column ];
// }

// error C2092: '[]' array element type cannot be function
// SPixel& operator[][]( const int Row, const int Column )

SPixel& Pixel( const int Row, const int Column )
{
return Data_[ Columns_ * Row + Column ];
}

private:
SPixel* Data_;
int Rows_;
int Columns_;

// No copy or assignment yet so disable by making private.
CMyBitmap ( CMyBitmap const& ) {};
CMyBitmap& operator=( CMyBitmap const& ) {};

};

Can we override 2d array access?


Certainly. But...
[][] is not an operator, it's two instances of the single
operator []. If you have your operator[] do the 'right
thing', you shouldn't have any problems using expressions
such as x[], x[][], x[][][], etc. Post back if you need
more help or an example.

-Mike

May 31 '06 #2

"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:5I******** ********@newsre ad2.news.pas.ea rthlink.net...

"Jim Langston" <ta*******@rock etmail.com> wrote in message
news:KB******** *******@fe04.lg a...
I wanted to do an operator override for [][] but couldnt' figure out the
syntax. I tried this (code that doesn't compile commented out with //:

class CMyBitmap
{
public:
CMyBitmap( int Rows, int Columns ): Rows_( Rows ), Columns_( Columns )
{
Data_ = new SPixel[ Rows * Columns ];
}
~CMyBitmap()
{
delete[] Data_;
}

// error C2804: binary 'operator [' has too many parameters
// SPixel& operator[]( const int Row, const int Column )
// {
// return Data_[ Columns_ * Row + Column ];
// }

// error C2092: '[]' array element type cannot be function
// SPixel& operator[][]( const int Row, const int Column )

SPixel& Pixel( const int Row, const int Column )
{
return Data_[ Columns_ * Row + Column ];
}

private:
SPixel* Data_;
int Rows_;
int Columns_;

// No copy or assignment yet so disable by making private.
CMyBitmap ( CMyBitmap const& ) {};
CMyBitmap& operator=( CMyBitmap const& ) {};

};

Can we override 2d array access?


Certainly. But...
[][] is not an operator, it's two instances of the single
operator []. If you have your operator[] do the 'right
thing', you shouldn't have any problems using expressions
such as x[], x[][], x[][][], etc. Post back if you need
more help or an example.


I had goggled for operator[] but goggle doesn't seem to index special
characters (such as '[') so the hits weren't very orderly and it took me a
long time to even find the syntax for [] My manual didn't give me any
examples, time to get a new manual.

I would need an example please, as I don't know how to override[] to accept
two paramters but you seem to indicate it is two instances of []. What is
the 'right thing' or can you direct me to a web page on the subject? As I
said, in this case Google was not my friend.
May 31 '06 #3
Jim Langston posted:

I would need an example please, as I don't know how to override[] to
accept two paramters but you seem to indicate it is two instances of
[]. What is the 'right thing' or can you direct me to a web page on
the subject? As I said, in this case Google was not my friend.

I only spent fifteen minutes on this, so it's by no means perfect.

Untested code:
class ChessBoard {
public:

class Square {
public:
enum SquareContents {
empty, pawn, castle, horse, bishop, queen, king } contents;

Square &operator=( SquareContents const sc )
{
contents = sc;
return *this;
}
};
Square squares[64];
class HorizontalCoord inate {
private:

ChessBoard &cb;
unsigned const x;

public:

HorizontalCoord inate(ChessBoar d &arg_cb, unsigned const arg_x)
: cb(arg_cb), x(arg_x) {}

Square &operator[]( unsigned const y )
{
return cb.squares[ x * 8 + y ];
}
};
HorizontalCoord inate operator[](unsigned const x)
{
return HorizontalCoord inate(*this, x);
}

};

int main()
{
ChessBoard board;

board[3][5] = ChessBoard::Squ are::bishop;
}
As you can see, a simple member function (or even function-style
operator) would probably be better.

-Tomás
May 31 '06 #4

"Jim Langston" <ta*******@rock etmail.com> wrote in message
news:KB******** *******@fe04.lg a...
I wanted to do an operator override for [][] but couldnt' figure out the
syntax. I tried this (code that doesn't compile commented out with //:

class CMyBitmap
{
public:
CMyBitmap( int Rows, int Columns ): Rows_( Rows ), Columns_( Columns )
{
Data_ = new SPixel[ Rows * Columns ];
}
~CMyBitmap()
{
delete[] Data_;
}

// error C2804: binary 'operator [' has too many parameters
// SPixel& operator[]( const int Row, const int Column )
// {
// return Data_[ Columns_ * Row + Column ];
// }

// error C2092: '[]' array element type cannot be function
// SPixel& operator[][]( const int Row, const int Column )

SPixel& Pixel( const int Row, const int Column )
{
return Data_[ Columns_ * Row + Column ];
}

private:
SPixel* Data_;
int Rows_;
int Columns_;

// No copy or assignment yet so disable by making private.
CMyBitmap ( CMyBitmap const& ) {};
CMyBitmap& operator=( CMyBitmap const& ) {};

};

Can we override 2d array access?


You should declare your operator as

something operator [] (int Row);

Then "something" must define

SPixel &operator [] (int Column);

The question is, what is "something" ? The best thing is probably to make it
a separate class. However, a well known cheat is to make "something" an
SPixel*, which automatically provides this second operator by the usual
rules for subscripting a pointer. Hence

SPixel *operator [] (int Row) {return Row * Columns_;}

will do it!

Cy
May 31 '06 #5

Jim Langston wrote:
I wanted to do an operator override for [][] but couldnt' figure out the
syntax.


http://www.parashift.com/c++-faq-lit...html#faq-13.10

May 31 '06 #6
Tomás posted:

I only spent fifteen minutes on this, so it's by no means perfect.

Taking Cy's trick on-board, you could change it to:
class ChessBoard {
public:

class Square {
public:
enum SquareContents {
empty, pawn, castle, horse, bishop, queen, king } contents;

Square &operator=( SquareContents const sc )
{
contents = sc;
return *this;
}
};

Square squares[64];
Square *operator[](unsigned const x)
{
return squares + 8 * (x-1);
}

};

int main()
{
ChessBoard board;

board[3][5] = ChessBoard::Squ are::bishop;
}
-Tomás
May 31 '06 #7

"Tomás" <No.Email@Addre ss> wrote in message
news:Tl******** **********@news .indigo.ie...
Jim Langston posted:

I would need an example please, as I don't know how to override[] to
accept two paramters but you seem to indicate it is two instances of
[]. What is the 'right thing' or can you direct me to a web page on
the subject? As I said, in this case Google was not my friend.

I only spent fifteen minutes on this, so it's by no means perfect.

Untested code:
class ChessBoard {
public:

class Square {
public:
enum SquareContents {
empty, pawn, castle, horse, bishop, queen, king } contents;

Square &operator=( SquareContents const sc )
{
contents = sc;
return *this;
}
};
Square squares[64];
class HorizontalCoord inate {
private:

ChessBoard &cb;
unsigned const x;

public:

HorizontalCoord inate(ChessBoar d &arg_cb, unsigned const arg_x)
: cb(arg_cb), x(arg_x) {}

Square &operator[]( unsigned const y )
{
return cb.squares[ x * 8 + y ];
}
};
HorizontalCoord inate operator[](unsigned const x)
{
return HorizontalCoord inate(*this, x);
}

};

int main()
{
ChessBoard board;

board[3][5] = ChessBoard::Squ are::bishop;
}
As you can see, a simple member function (or even function-style
operator) would probably be better.


Thank you. Works well. This is my solution if anyone is interested.

union SPixel
{
struct {
unsigned char B, G, R, A;
};
unsigned long Value;
};

class CMyBitmap
{
public:
CMyBitmap( int Rows, int Columns ): Rows_( Rows ), Columns_( Columns )
{
Data_ = new SPixel[ Rows * Columns ];
}
~CMyBitmap()
{
delete[] Data_;
}
SPixel& Pixel( const int Row, const int Column )
{
if ( Row > Rows_ || Row < 0 )
throw std::string( "Out of bounds for row" );
else if ( Column > Columns_ || Column < 0 )
throw std::string( "Out of bounds for column" );
else
return Data_[ Columns_ * Row + Column ];
}

class HorizCoord
{
public:
HorizCoord( CMyBitmap& Bitmap, const int Row ): Bitmap_( Bitmap ),
Row_( Row ) {}
SPixel& operator[]( const int Column )
{
if ( Column > Bitmap_.Columns _ || Column < 0 )
throw std::string( "Out of bounds for column" );
else
return Bitmap_.Data_[ Bitmap_.Columns _ * Row_ + Column ];
}
private:
CMyBitmap& Bitmap_;
const Row_;
};

HorizCoord operator[] (int const Row)
{
if ( Row > Rows_ || Row < 0 )
throw std::string( "Out of bounds for row" );
else
return HorizCoord(*thi s, Row);
}

private:
SPixel* Data_;
int Rows_;
int Columns_;

// No copy or assignment yet so disable by making private.
CMyBitmap ( CMyBitmap const& ) {};
CMyBitmap& operator=( CMyBitmap const& ) {};

};

int main()
{
SPixel Pixel;
Pixel.Value = 0x01020304;
std::cout << "0x01020304 by color: " << (int) Pixel.A << " " << (int)
Pixel.R << " " << (int) Pixel.G << " " << (int) Pixel.B << std::endl;

CMyBitmap BitMap( 100, 100 );

BitMap.Pixel(10 , 10).R = 255;
BitMap.Pixel(10 , 10).B = 255;
BitMap.Pixel(10 , 10).G = 255;
BitMap.Pixel(10 , 10).A = 255;
std::cout << "All bits set by value: " <<BitMap.Pixel( 10, 10).Value <<
std::endl;

BitMap[15][15].R = 128;
BitMap[15][15].B = 129;
BitMap[15][15].G = 130;
BitMap[15][15].A = 131;
std::cout << "Set using [][]: " << BitMap.Pixel(15 , 15).Value <<
std::endl;

BitMap.Pixel(20 , 20).Value = 0xFFFF0000;
std::cout << "0xFFFF0000 by color: " << (int) BitMap.Pixel(20 , 20).A <<
" " << (int) BitMap.Pixel(20 , 20).R << " " << (int) BitMap.Pixel(20 , 20).G
<< " " << (int) BitMap.Pixel(20 , 20).B << std::endl;

// Lets just prove that Intel is Bigendian.
unsigned char* pchar = reinterpret_cas t<unsigned char*>(
&(BitMap.Pix el( 20, 20 ).Value ) );
std::cout << "First Byte:" << (int) *(pchar++) << std::endl;
std::cout << "Second Byte:" << (int) *(pchar++) << std::endl;
std::cout << "Third Byte:" << (int) *(pchar++) << std::endl;
std::cout << "Fourth Byte:" << (int) *pchar << std::endl;

std::string wait;
std::cin >> wait;
}
May 31 '06 #8

"Cy Edmunds" <sp************ ***@rochester.r r.com> wrote in message
news:Wv******** *********@twist er.nyroc.rr.com ...

"Jim Langston" <ta*******@rock etmail.com> wrote in message
news:KB******** *******@fe04.lg a...
I wanted to do an operator override for [][] but couldnt' figure out the
syntax. I tried this (code that doesn't compile commented out with //:

class CMyBitmap
{
public:
CMyBitmap( int Rows, int Columns ): Rows_( Rows ), Columns_( Columns )
{
Data_ = new SPixel[ Rows * Columns ];
}
~CMyBitmap()
{
delete[] Data_;
}

// error C2804: binary 'operator [' has too many parameters
// SPixel& operator[]( const int Row, const int Column )
// {
// return Data_[ Columns_ * Row + Column ];
// }

// error C2092: '[]' array element type cannot be function
// SPixel& operator[][]( const int Row, const int Column )

SPixel& Pixel( const int Row, const int Column )
{
return Data_[ Columns_ * Row + Column ];
}

private:
SPixel* Data_;
int Rows_;
int Columns_;

// No copy or assignment yet so disable by making private.
CMyBitmap ( CMyBitmap const& ) {};
CMyBitmap& operator=( CMyBitmap const& ) {};

};

Can we override 2d array access?


You should declare your operator as

something operator [] (int Row);

Then "something" must define

SPixel &operator [] (int Column);

The question is, what is "something" ? The best thing is probably to make
it a separate class. However, a well known cheat is to make "something" an
SPixel*, which automatically provides this second operator by the usual
rules for subscripting a pointer. Hence

SPixel *operator [] (int Row) {return Row * Columns_;}

will do it!


This is an excellant solution, but I can't check for column overflow. I
think I'll keep the existing solution I have right now, but keep your's in
mind for other classes.

Thanks!
May 31 '06 #9

Noah Roberts wrote:
Jim Langston wrote:
I wanted to do an operator override for [][] but couldnt' figure out the
syntax.


http://www.parashift.com/c++-faq-lit...html#faq-13.10


I recommend NOT following this particular FAQ.
It uses contrive logic to support promoting the use of non-standard
syntax to reference a matrix.

I recommend using standard syntax [][] over more ambiguous ()() method.
I also recommmend using vector<vector<T > > type.

See following links for example implementations :
http://code.axter.com/dynamic_2d_array.h
http://www.codeguru.com/forum/showthread.php?t=231046
http://www.codeguru.com/forum/showth...hreadid=297838

May 31 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3160
by: Woodmon | last post by:
Example of my CSS follows: <style type="text/css" media="screen"> BODY { color: white } A:link { color: 66CCFF; } A:visited { color: CC66FF; } A:active { color: CC66FF; } A:hover { color: white; background-color: #0099cc; text-decoration: #000000;}
0
4004
by: Craig Schneider | last post by:
// Is there any way to override the XML Serialization of the following SimpleClass // to turn off the DefaultValue of a boolean? Sure, I can override the DefaultValue from // true to false, but that is not what I want/need. I really need to just override the fact // that the developer ever supplied a DefaultValue. Setting an override DefaultValue of null // or "new object()" errors. Any help would be appreciated.
7
6452
by: Dave Y | last post by:
I am a newbie to C# and am having trouble trying to override a ListView property method. I have created a new class derived from the Forms.Listview and I cannot figure out the syntax to override ListView.Items.Add(), . I see that it is a virtual method so it should be easy to do. If anyone can help I would appreciate it greatly. I can do what I need to do in a different way this would just make everything significantly cleaner and eaasier...
5
2615
by: Mark Broadbent | last post by:
Oh yes its that chestnut again! Ive gone over the following (http://www.yoda.arachsys.com/csharp/faq/ -thanks Jon!) again regarding this subject and performed a few of my own tests. I have two classes yClass which inherits xClass. xClass has a virtual method which simply writes a line of text stating its origin, yClass implements the same method which writes a line of text stating its origin also (i.e. "From yClass"). I ran the...
2
4550
by: Flip | last post by:
In java, the default for methods is override. In c# that is not the case. This talks about two classes, the base class and the overriding class. What happens when you have a third class in the mix, extending the second class, how can you indicate the method in the third class is overridding the overridden method? Do you declare the second method to be virtual override? ClassA ------------- virtual DrawWindow(){//code} ^
5
9607
by: Stoyan | last post by:
Hi All, I don't understand very well this part of MSDN: "Derived classes that override GetHashCode must also override Equals to guarantee that two objects considered equal have the same hash code; otherwise, Hashtable might not work correctly." Does any one know, why we must also override Equals, Please give my an example:) Thanks, Stoyan
15
2554
by: John Salerno | last post by:
Hi all. I have a question about virtual and override methods. Please forgive the elementary nature! First off, let me quote Programming in the Key of C#: "Any virtual method overridden with 'override' remains a virtual method for further descendent classes." Now here's my question: Let's say you have base class A, and subclasses B and C. Class A contains a virtual method, and B contains an override method. If C didn't have an...
2
4060
by: Adriano Coser | last post by:
Hello. After I converted my .net code to the new VC2005 syntax I started to get C4490 on my ExpandableObjectConverter subclass overrides. The GetProperties method is no longer called by the PropertyGrid when I use my subclass as a type converter. Can anyone tell me what has changed? What's the correct way to override GetProperties method? Here's the code for my class:
8
5501
by: bdeviled | last post by:
I am deploying to a web environment that uses load balancing and to insure that sessions persist across servers, the environment uses SQL to manage sessions. The machine.config file determines how all applications will use sessions and to insure that all application use this method, the session properties cannot be overriden. Within the sessionstate tags, the webadmin (upon my request)r emoved the property for timeout, hoping that...
5
4536
by: Marcel Hug | last post by:
Hi NG ! I'm new in C# and I'm reading a book about the fundamentals and concepts. In the chapter Methods it's written to use virtual, if i would like to override the method in a subclass. This I've to do by using override. It's also written, that's possible to "hide" the base class method by using the new key word. Because I've already written some C# code and I didn't know anything
0
9719
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9598
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10371
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10373
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10111
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9192
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5683
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3852
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3010
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.