Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ []c+中get和set操作的运算符重载+;_C++_Arrays_Reference_Operator Overloading - Fatal编程技术网

C++ []c+中get和set操作的运算符重载+;

C++ []c+中get和set操作的运算符重载+;,c++,arrays,reference,operator-overloading,C++,Arrays,Reference,Operator Overloading,我正在上以下课程: class mem { private: char _memory[0x10000][9]; public: const (&char)[9] operator [] (int addr); } 我的目标是能够像数组一样使用mem类,而稍后的实现将更加复杂。所以,我应该能够 像“mem[0x1234]”一样访问它,以返回对9个字符数组的引用 像“mem[0x1234]=“12345678\0”一样写入它 这就是我所尝试的: #incl

我正在上以下课程:

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

public: 
    const (&char)[9] operator [] (int addr);    
}
我的目标是能够像数组一样使用
mem
类,而稍后的实现将更加复杂。所以,我应该能够

  • 像“mem[0x1234]”一样访问它,以返回对9个字符数组的引用
  • 像“mem[0x1234]=“12345678\0”一样写入它
这就是我所尝试的:

#include "mem.h"

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

但是,它说方法“必须有一个返回值”,我想我已经定义为
(&char)[9]
,但是在这个定义中,我得到了错误消息“expected a 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 mem
{
private:
    char _memory[0x10000][9];

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

运算符[]
是一个接受int的函数

operator[](int addr)
返回一个引用

& operator[](int addr)
到长度为9的数组

(&operator[](int addr))[9]
常量字符的

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);
std::array\u内存;
常量std::数组和运算符[](int addr);