简体   繁体   中英

[] Operator overloading for get and set operation in c++

I'm having the following class:

class mem
{
private:
    char _memory[0x10000][9];

public: 
    const (&char)[9] operator [] (int addr);    
}

My goal is to be able to use the mem class like an array while the implementation will be more complex later. So, I should be able to

  • access it like 'mem[0x1234]' to return a reference to an array of 9 chars
  • write to it like 'mem[0x1234] = "12345678\\0";'

This is what I tried:

#include "mem.h"

const (&char)[9] mem::operator [] (int addr)
{
    return &_memory[addr];
}

However, it says that the method "must have a return value", which I thought I have defined as (&char)[9] , but as this definition I get the error message "expected an identifier".

operator[] is a function taking int

operator[](int addr)

that returns a reference

& operator[](int addr)

to an array of length 9

(&operator[](int addr))[9]

of const char

const char (&operator[](int addr))[9]

That said, don't do that. Use typedef s to simplify:

typedef const char (&ref9)[9];
ref9 operator[](int addr);

That said, don't do that either.

std::array<std::array<char, 9>, 0x10000> _memory;
const std::array<char, 9>& operator[](int addr);

Write the following way

#include "mem.h"

const char ( & mem::operator [] (int addr) const )[9]
{
    return _memory[addr];
}

also you can add a non-constant operator

char ( & mem::operator [] (int addr) )[9]
{
    return _memory[addr];
}

The class definition will look like

class mem
{
private:
    char _memory[0x10000][9];

public: 
    const char ( & operator [] (int addr) const )[9];    
    char ( & operator [] (int addr) )[9];    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM