【发布时间】:2012-09-11 13:12:09
【问题描述】:
假设我有这样一个结构:
struct Foo
{
const int bar;
const char baz;
Foo& operator=(const Foo& other)
{
memcpy(this,&other,sizeof(Foo)); //How am I supposed to write this decently?
return *this;
}
}
我希望 Foo 的所有字段都是最终的,并且我希望 Foo 类型的变量的行为就像其他原始值类型一样。说,int,我们当然可以这样写:
int i = 0;
i = 42;
Foo foo = {007,'B'}
foo = {42,'X'}
但是对于我可怜的 Foo 类型,我是否必须求助于 memcpy 之类的方法来解决类型安全检查?我知道我可以删除 const 修饰符,将字段标记为私有并添加一些 getter,但这不是重点。我只是想知道是否有一种体面的方式来编写 = 运算符的内容。
提前致谢!
~~~~~
查看以下示例:
//If the = op is not implemented, this won't compile
Foo stat;
for(int i=0;i!=100;++i)
{
stat = func(i);
if(stat.bar == 0)...
}
//But weird thing is, if I declare the 'stat' inside the for block, it works just fine with gcc
for(int i=0;i!=100;++i)
{
Foo stat = func(i);
//printf("%p\n",&stat); => same variable same address!!
if(stat.bar == 0)...
}
这对你有意义吗?
【问题讨论】:
-
这毫无意义(这就是为什么你不能让它工作)。你想要 const 一个“全常量”类型是可变的?下定决心。不,甚至
memcpy也做不到。最终结果是未定义的行为。准备好看到编译器做你没有要求它做的事情。 -
@R.MartinhoFernandes - 为什么我不能使用 memcpy?如果它有确定的大小和确定的地址,为什么我不能往它占用的内存卡盘里写东西呢?
-
这不是很明显吗?因为成员是
const!
标签: c++ overloading operator-keyword