成员全是常量的类,怎么实现赋值构造函数
发布网友
发布时间:2023-07-12 19:26
我来回答
共1个回答
热心网友
时间:2024-12-11 16:26
#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;
}