复制构造函数、赋值运算符C++
Copy Constructors, Assignment Operator C++
我对OOP很陌生,仍在尝试理解构造函数的所有概念。我有一个包含一些数据的类,我必须做一个Copy Constructor
和Assignment Operator
,但是,由于这是我第一次做这样的事情,我不确定我写的内容是否有意义。所以,我问我写的是否是有效的复制构造函数和赋值运算符。该类保存在一个名为BKS.h
谢谢! 这是类:
#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;
template <class T>
class BKS final
{
public:
struct Item
{
T identifier;
int weight;
int benefit;
};
BKS() {}
BKS(const BKS<T> ©);
BKS(const vector<Item> &items) : itemlist_{items} {}
BKS(const vector<pair<int, int>> &weight_benefit_list);
BKS<T> &operator=(const BKS<T> ©);
// some methods ....
private:
vector<Item> itemlist_;
vector<int> current_selection_;
int current_capacity_ {0};
int maximal_benefit_ {0};
};
复制构造函数和辅助运算符:
#include "bks.h"
template <class T>
BKS<T>::BKS(const BKS<T> ©) // copy constructor
{
std::vector<Item> itemlist_ = copy.itemlist_;
std::vector<int> current_selection_ = copy.current_selection_;
int current_capacity_ = copy.current_capacity_;
int maximal_benefit_ = copy.maximal_benefit_;
}
template <class T>
BKS<T> &BKS<T>::operator=(const BKS<T> ©)
{
if (© != this)
{ // check for self-assignment
this->itemlist_ = copy.itemlist_;
this->current_selection_ = copy.current_selection_;
this->current_capacity_ = copy.current_capacity_;
this->maximal_benefit_ = copy.maximal_benefit_;
}
return *this;
}
也欢迎任何关于构造函数的一般建议:)
如果你的导师坚持你必须声明特殊成员,但没有给出如何的指导,那么最好的方法是:
template <class T>
class BKS final
{
public:
~BKS() = default;
BKS(const BKS &) = default;
BKS& operator=(const BKS &) = default;
BKS(BKS &&) = default;
BKS& operator=(BKS &&) = default;
/* other members... */
};
如果您的教师不要求您声明它们,而只要求它们存在,最好的方法是
template <class T>
class BKS final
{
public:
/* other members... */
};
当您在不声明复制构造函数、复制赋值运算符和析构函数的情况下创建新类时,编译器将声明自己的复制构造函数、复制赋值运算符和析构函数版本。 此外,如果您不声明构造函数,编译器将为您隐式声明一个构造函数。
所有这些默认编译器生成的函数都是public
和inline
的。请注意,隐式声明的析构函数是非虚拟的。
那么默认构造函数、默认复制构造函数、默认复制赋值运算符和默认析构函数会做什么呢?
默认构造函数(隐式声明或用户定义(:调用类的基和非静态成员的默认构造函数;
默认复制构造函数(隐式声明(和默认复制赋值运算符(隐式声明(:将源对象的每个非静态数据成员复制到目标对象;
默认析构函数(隐式声明或用户定义(:调用基类的析构函数和派生类的成员。
在您的例子中,您的非静态数据成员将由默认的复制构造函数和默认的复制赋值运算符复制。无需定义自己的复制构造函数和复制赋值运算符,除非您要为复制构造函数和复制赋值运算符添加特定行为。
引用:
https://en.cppreference.com/w/cpp/language/default_constructor
https://www.ibm.com/support/knowledgecenter/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/cplr380.htm
书籍:斯科特·迈耶斯(Scott Meyers(的"有效C++",第2章
- 重载Singly Linked List中的赋值运算符
- 使用赋值运算符重载从类中返回jobject
- 标准库类型的赋值运算符的引用限定符
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 基类和派生类的多态赋值运算符
- 为用户定义的类正确调用复制构造函数/赋值运算符
- CRTP 中的复制赋值运算符 - gcc vs clang 和 msvc
- 为什么初始化时没有调用重载赋值运算符?
- 赋值运算符重载和自赋值
- C++矢量复制构造函数和赋值运算符是否也复制保留空间?
- Qt PL/SQL - 赋值运算符 - 字符串缓冲区太小
- 对 r 值使用移动赋值运算符时的异常
- 由于没有使用赋值运算符,映射的值是如何初始化的?
- 默认赋值运算符如何在实际 STL 中实现
- 使用赋值运算符复制 std::vector
- C++ 通过自定义赋值运算符隐式转换函数参数
- 赋值运算符的奇怪行为
- C++赋值运算符,我们可以用 copy 替换它吗?