作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个结构来存储和操作内存地址。我决定将其中一个字段从 int
更改为 const int
以确保它是只读的,突然间我定义的 operator-() 提示以下内容留言:
function "memAddress::operator=(const memAddress &)" (declared implicitly) cannot be referenced -- it is a deleted function
这是代码,
struct memAddress
{
// memory location variables
int die = 0;
int plane = 0;
int page = 0;
int column = 0;
int block = _BLOCK_STARTING_ADDRESS;
memAddress() {}
memAddress(const memAddress &m)
{
die = m.die;
plane = m.plane;
page = m.page;
column = m.column;
block = m.block;
}
bool operator<(const memAddress &m)
{
if (die > m.die)
return false;
else if (die == m.die)
{
if (plane > m.plane)
return false;
else if (plane == m.plane)
{
if (block > m.block)
return false;
else if (block == m.block)
{
if (page > m.page)
return false;
else if (page == m.page)
{
if (column >= m.column)
return false;
else
return true;
}
else
return true;
}
else
return true;
}
else
return true;
}
else
return true;
}
bool operator==(const memAddress &m)
{
if (die == m.die &&
plane == m.plane &&
block == m.block &&
page == m.page &&
column == m.column)
{
return true;
}
return false;
}
bool operator<=(const memAddress &m)
{
if ((*this < m) || (*this == m))
return true;
return false;
}
bool operator>(const memAddress &m)
{
if (!(*this <= m))
return true;
return false;
}
bool operator>=(const memAddress &m)
{
if ((*this > m) || (*this == m))
return true;
return false;
}
memAddress operator-(const memAddress &m)
{
memAddress diff, a1, a2;
if (*this < m)
{
a2 = m; // **error**
a1 = *this; // **error**
}
else
{
a2 = *this; // **error**
a1 = m; // **error**
}
diff.die = a2.die - a1.die;
diff.plane = a2.plane - a1.plane;
diff.block = a2.block - a1.block;
diff.page = a2.page - a1.page;
diff.column = a2.column - a1.column;
return diff;
}
private:
const int _BLOCK_STARTING_ADDRESS = 2; // **modifier added here**
};
我不知道为什么会发生这种情况 - 如果删除修饰符,代码可以正常工作。
为什么将字段修饰符更改为 const
会导致此行为?我该如何绕过它?
最佳答案
您使用全部大写(以及使用它来初始化 block
)表明您打算将 _BLOCK_STARTING_ADDRESS
作为所有实例的类常量。
所以首先也是最重要的,让它成为静态的
static const int _BLOCK_STARTING_ADDRESS = 2;
为什么?因为否则它是每个实例的数据成员。这意味着每个实例都有一小部分必须是 const
,并且默认情况下您不能分配给该 const 位。因此,编译器无法为您生成默认赋值运算符。
另外,作为一个方面没有。以 _[A-Z]
开头的名称保留给 C++ 实现以供任何使用。为了避免鼻恶魔的可能性,我建议你改变你的命名方案。甚至可能与less shouting ?
关于c++ - 将字段声明为 const 调用 "function operator=(const memAddress &) cannot be referenced -- it is a deleted function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52737900/
我是一名优秀的程序员,十分优秀!