【发布时间】:2011-05-06 16:09:50
【问题描述】:
考虑以下几点:
class A {
public:
const int c; // must not be modified!
A(int _c)
: c(_c)
{
// Nothing here
}
A(const A& copy)
: c(copy.c)
{
// Nothing here
}
};
int main(int argc, char *argv[])
{
A foo(1337);
vector<A> vec;
vec.push_back(foo); // <-- compile error!
return 0;
}
显然,复制构造函数是不够的。我错过了什么?
编辑:
办公室。我无法在operator=() 方法中更改this->c,所以我看不到如何使用operator=()(尽管std::vector 需要)。
【问题讨论】:
-
什么是编译错误? 不要含糊其辞,成为ace;写一个propertest-case!
-
我认为你有一个选择:要么失去 const,要么失去使用向量的能力。如果您开始解决它并允许
operator=修改 const 成员,那么您现在已经为任何一段代码提供了执行相同操作的方法。 -
const int c; // 不得修改!您在上面的评论,这是否意味着“c”不应该被使用 A 类的对象或 A 类本身的成员修改?
-
@anand: c 只能在构造函数中设置。在我的具体情况下,我有一个指向某个父节点的指针。任务 * 常量父级;此指针不得重新定位,因此不允许在课堂内或外部对 c 进行更改。
-
@eisbaw:对我来说,选择 'const int c' 作为 A 类的成员是问题的根本原因。因此我的问题。有一个 operator=() 并使用 const_cast 来抛弃 const 来为“c”赋值,这听起来像是修复编译器错误的技巧,而不是解决实际问题的方法。
标签: c++ vector const-correctness