我有一个类来读取/写入外部随机存取存储器。
.h文件:
class RAM {
private:
bool Read(char *Buffer, size_t BytesToRead, uint32_t StartAddress);
bool Write(char *Buffer, size_t BytesToWrite, uint32_t StartAddress);
class proxy {
private:
size_t _index;
public:
proxy(size_t i);
void operator=(char rhs);
operator char();
}
public:
proxy operator[](size_t i);
};
.cpp文件:
RAM::proxy RAM::operator[](size_t i) {
return proxy(i);
}
proxy::proxy(size_t i) {
_index = i;
}
void proxy::operator=(char rhs) {
Write(&rhs, 1, _index); // error
}
RAM::proxy::operator char() {
char Buf[1];
Read(Buf, 1, _index); // error
return Buf[0];
}
读取和写入是处理对RAM的低级访问的函数。没有其他方法可以读取或写入RAM。我尝试使用proxy class in rvalue - how to implement assignment operator?但无法正确调整它:
错误:无法调用成员函数' bool RAM :: Write(char *,size_t,uint32_t)'没有对象写(& rhs,1,_index)
错误:无法调用成员函数' bool RAM :: Read(char *,size_t,uint32_t)'没有对象读(Buf,1,_index)
还有其他东西要求读写,所以我可能无法使它们成为静态的。另外我认为在创建RAM对象时它们已经被实例化了。
答案 0 :(得分:1)
感谢PeteBecker我能够提出一个有效的代码。另外,我没有在最初的问题中提出问题,但是我忽略了测试直接任务,结果证明是一个不同的野兽。
class RAM {
private:
// changed 1st arg to void*, because type doesn't really matter.
bool Read(void *Buffer, size_t BytesToRead, uint32_t StartAddress);
bool Write(void *Buffer, size_t BytesToWrite, uint32_t StartAddress);
class proxy {
private:
size_t _index;
RAM *_parentPtr; // <-- added
public:
proxy(size_t i, RAM *ptr) {
_index = i;
_parentPtr = ptr; // <-- added
}
void operator=(char rhs) {
Write(&rhs, 1, _index); // works now
}
void operator=(proxy rhs) { // new function for direct assignment
char temp = rhs;
Write(&temp, 1, _index);
}
operator char() const {
char Buf[1];
Read(Buf, 1, _index); // works now
return Buf[0];
}
}
public:
proxy operator[](size_t i) {
return proxy(i, this);
}
};
花了很长时间才弄清楚我必须通过临时变量请求rhs的值来执行operator char() const
。作为参考传递不会做到。