[] C++中get和set操作的运算符重载
[] Operator overloading for get and set operation in c++
我有以下 class:
class mem
{
private:
char _memory[0x10000][9];
public:
const (&char)[9] operator [] (int addr);
}
我的目标是能够像数组一样使用 mem
class,而稍后的实现会更复杂。所以,我应该可以
- 像 'mem[0x1234]' 一样访问它 return 对 9 个字符的数组的引用
- 像'mem[0x1234] = "12345678[=31=]";'
这样写
这是我试过的:
#include "mem.h"
const (&char)[9] mem::operator [] (int addr)
{
return &_memory[addr];
}
然而,它说方法"must have a return value",我以为我已经定义为(&char)[9]
,但是作为这个定义我得到错误消息"expected an identifier"。
写成下面的方式
#include "mem.h"
const char ( & mem::operator [] (int addr) const )[9]
{
return _memory[addr];
}
你也可以添加一个非常量运算符
char ( & mem::operator [] (int addr) )[9]
{
return _memory[addr];
}
class 定义看起来像
class mem
{
private:
char _memory[0x10000][9];
public:
const char ( & operator [] (int addr) const )[9];
char ( & operator [] (int addr) )[9];
}
operator[]
是一个接受 int
的函数
operator[](int addr)
那个returns一个参考[=19=]
& operator[](int addr)
到长度为 9 的数组
(&operator[](int addr))[9]
共 const char
const char (&operator[](int addr))[9]
就是说,不要那样做。使用typedef
s简化:
typedef const char (&ref9)[9];
ref9 operator[](int addr);
也就是说,也不要那样做。
std::array<std::array<char, 9>, 0x10000> _memory;
const std::array<char, 9>& operator[](int addr);
我有以下 class:
class mem
{
private:
char _memory[0x10000][9];
public:
const (&char)[9] operator [] (int addr);
}
我的目标是能够像数组一样使用 mem
class,而稍后的实现会更复杂。所以,我应该可以
- 像 'mem[0x1234]' 一样访问它 return 对 9 个字符的数组的引用
- 像'mem[0x1234] = "12345678[=31=]";' 这样写
这是我试过的:
#include "mem.h"
const (&char)[9] mem::operator [] (int addr)
{
return &_memory[addr];
}
然而,它说方法"must have a return value",我以为我已经定义为(&char)[9]
,但是作为这个定义我得到错误消息"expected an identifier"。
写成下面的方式
#include "mem.h"
const char ( & mem::operator [] (int addr) const )[9]
{
return _memory[addr];
}
你也可以添加一个非常量运算符
char ( & mem::operator [] (int addr) )[9]
{
return _memory[addr];
}
class 定义看起来像
class mem
{
private:
char _memory[0x10000][9];
public:
const char ( & operator [] (int addr) const )[9];
char ( & operator [] (int addr) )[9];
}
operator[]
是一个接受 int
operator[](int addr)
那个returns一个参考[=19=]
& operator[](int addr)
到长度为 9 的数组
(&operator[](int addr))[9]
共 const char
const char (&operator[](int addr))[9]
就是说,不要那样做。使用typedef
s简化:
typedef const char (&ref9)[9];
ref9 operator[](int addr);
也就是说,也不要那样做。
std::array<std::array<char, 9>, 0x10000> _memory;
const std::array<char, 9>& operator[](int addr);