gpt4 book ai didi

c++ - 复制具有 const vector 成员的类的构造函数

转载 作者:行者123 更新时间:2023-11-30 02:17:47 25 4
gpt4 key购买 nike

我的代码中有 OpenTable 类:

class OpenTable : public BaseAction {
public:
OpenTable(int id, std::vector<Customer *> &customersList);
OpenTable(const OpenTable& other);
private:
const int tableId;
const std::vector<Customer *> customers;
};

我需要为这个类实现一个复制构造函数(我知道这可能是一个糟糕的设计,但我被指示这样做)。我在尝试深度复制常量 vector customers 时遇到了问题。

我尝试了以下方法:

OpenTable::OpenTable(const OpenTable& other): tableId(other.tableId)
{
for(std::vector<Customer*>::const_iterator i=other.customers.begin(); i!=other.customers.end(); i++) {
customers.push_back((*i)->copy()); // copy returns a Customer*
}

但显然它无法编译,可能是因为 vector 是 const,因此我无法向其添加元素。

我收到以下错误:

no instance of overloaded function "std::vector<_Tp, _Alloc>::push_back 
[with _Tp=Customer *, _Alloc=std::allocator<Customer *>]" matches the
argument list and object (the object has type qualifiers that prevent a
match) -- argument types are: (Customer *) -- object type is: const
std::vector<Customer *, std::allocator<Customer *>>

注意:在参数化构造函数中,我只是浅复制,因为我可以。不过,这不适用于复制构造函数。

提前致谢。

最佳答案

最简单的解决方案是创建一个接受 const std::vector<Customer *> 的辅助函数。并返回 std::vector<Customer *>那是该论点的深层拷贝。然后,在您的构造函数的初始化列表中,使用该函数来初始化您的私有(private)成员。

可选地,该辅助函数可以是 privatestatic如果你想限制对它的访问,你的类(class)成员。这在构造函数或其初始化列表中是可以接受的,因为 static成员函数不依赖于类的非静态成员被初始化,因此不依赖于构造函数已经完成。

如果在进行深拷贝的辅助函数中出现问题,辅助函数将需要适本地清理(例如,如果 Customer 对象之一的构造失败,则需要释放任何成功构造的对象以避免内存泄漏)。

关于c++ - 复制具有 const vector 成员的类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com