我对OOP还是很陌生,仍在尝试理解构造函数的所有概念。我有一个类,里面有一些数据,我必须制作一个Copy Constructor
和Assignment Operator
,但是,由于这是我第一次这样做,所以我不确定我写的内容是否有意义。所以,我问我写的内容是否是有效的复制构造函数和赋值运算符。该类保存在名为BKS.h
的文件中,谢谢!
这是类(class):
#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... */
};
关于c++ - 复制构造函数,赋值运算符C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62755138/