c++ - 复制构造函数,赋值运算符C++

标签 c++ constructor

我对OOP还是很陌生,仍在尝试理解构造函数的所有概念。我有一个类,里面有一些数据,我必须制作一个Copy ConstructorAssignment 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> &copy);
    BKS(const vector<Item> &items) : itemlist_{items} {}
    BKS(const vector<pair<int, int>> &weight_benefit_list);
    BKS<T> &operator=(const BKS<T> &copy);
    // 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)                 // 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> &copy)
{
    if (&copy != 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/

相关文章:

javascript - 关于 return 关键字

c++ - 模板方法 enable_if 特化

c# - Visual Studio 无法识别我的构造函数?

javascript - 什么时候真正使用对象的 `.constructor`属性

c++ - 打印一个 unicode 拉丁字母 (utf8)

c++ - 向构造函数调用添加括号会导致 xlc C++ 编译器出现重复参数错误

C++ : can I do some processing before calling another constructor?

c++ - 高CPU负载。 C++/sfml

c++ - 相邻差异使用什么语法?

c# - 如何确定鼠标是否指向光标下窗口的最大化按钮