读书人

成员全是常量的类如何实现赋值构造函

发布时间: 2013-12-20 00:23:10 作者: rapoo

成员全是常量的类,怎么实现赋值构造函数
成员全是常量的类,怎么实现“赋值(operator = )”函数。

我有一个类, 里面只有两个const成员, 然后我就把这个类放到了vector里面, 发现编译报错。 提示 operator = (编译器帮合成的)不正确。 具体提示我忘记了,但是肯定是去掉const修饰, 编译就木有问题了。

想知道, 成员变量有const的类,怎么实现赋值构造函数。
部分成员的const语义限制了赋值操作,局部const语义导致整体const语义。
如果执着的话,来个就地重新构造。测试:


部分成员的const语义限制了赋值操作,局部const语义导致整体const语义。
如果执着的话,来个就地重新构造。测试:
#include <vector>
#include <algorithm>
#include <iterator>

struct Item
{
const int id;

Item(int _id):
id(_id)
{}

Item& operator=(Item const &other)
{
if (this == &other)
return *this;
this->~Item();
return *new(this)Item(other.id);
}
};

std::ostream& operator<<(std::ostream& s, const Item& p)
{
return s << "Item" << '(' << p.id << ')';


}

int main()
{
std::vector<Item> v;
Item a(10);
v.push_back(Item(1));
v.push_back(Item(2));
v.push_back(Item(4));
v.push_back(a);

std::copy(v.begin(), v.end(), std::ostream_iterator<Item>(std::cout,","));

return 0;
}



++
大概只能这么处理了,感觉这么做,比不用const 还奇怪。
不用 const 因为既然你都复制了,自然不用const 比较好

读书人网 >C++

热点推荐