提问者:小点点

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


我对OOP很陌生,还在努力理解构造函数的所有概念。 我有一个带有一些数据的类,我必须制作一个复制构造函数赋值运算符,然而,由于这是我第一次做这样的事情,我不确定我所写的内容是否有意义。 所以,我在问我所写的是不是有效的复制构造函数和赋值运算符。 类保存在名为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> &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;
}

此外,欢迎任何有关构造函数的一般性建议:)


共2个答案

匿名用户

如果您的教师坚持您必须声明特殊成员,但没有给出如何声明的指导,那么最好的方法是:

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... */
};

匿名用户

当您创建新类而不声明复制构造函数,复制赋值运算符和析构函数时,编译器将声明它们自己版本的复制构造函数,复制赋值运算符和析构函数。 此外,如果您不声明构造函数,编译器将隐式地为您声明一个。

所有这些默认编译器生成的函数都是公共内联。 请注意,隐含声明的析构函数是非虚拟的。

那么默认构造函数,默认复制构造函数,默认复制赋值运算符和默认析构函数会做什么呢?

>

  • 默认构造函数(隐式声明或用户定义):调用类的基和非静态成员的默认构造函数;

    默认复制构造函数(隐式声明)和默认复制赋值运算符(隐式声明):将源对象的每个非静态数据成员复制到目标对象;

    默认析构函数(隐式声明或用户定义):调用基类和派生类成员的析构函数。

    在这里,您的非静态数据成员将被默认复制构造函数和默认复制赋值运算符复制。 不需要定义自己的复制构造函数和复制赋值运算符,除非您想为复制构造函数和复制赋值运算符添加特定的行为。

    参考资料:

    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

    本书:《有效的C++》,Scott Meyers著,第2章

  • 相关问题


    MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(复制|构造|函数|赋值|运算符|c++)' ORDER BY qid DESC LIMIT 20
    MySQL Error : Got error 'repetition-operator operand invalid' from regexp
    MySQL Errno : 1139
    Message : Got error 'repetition-operator operand invalid' from regexp
    Need Help?