定义复制构造函数和赋值操作符

defining copy constructor and assignment operator

本文关键字:赋值操作符 构造函数 复制 定义      更新时间:2023-10-16

这是我第一次用c++处理类。我想知道是否有人可以帮助我正确地为下面的类设计一个复制构造函数和一个赋值操作符。

下面的文章讨论了三的规则,

什么是三法则?

虽然,我的代码不是很清楚如何实现它。

INFO.h

#ifndef INFO_H
#define INFO_H
class INFO{
public:
        std::string label, type;
        unsigned int num;
        double x, y, z, velx, vely, velz;
        void print(std::ostream& stream);
        void mod_print(std::ostream& stream);
        void read(std::istream& stream);
        void mod_read(std::istream& stream);
        double distance(INFO *i,double L);
        INFO(std::istream& stream);
        INFO(){};
};
#endif

INFO.cpp

#include "INFO.h"
void INFO::print(std::ostream& stream)
{
        stream << label <<'t'<< type <<'t'<< num <<'t'<< x<<'t'<<y<<'t'<< z << 'n';
}
void INFO::mod_print(std::ostream& stream)
{
        stream << label <<'t'<< type <<'t'<< x<<'t'<<y<<'t'<< z << 'n';
}
void INFO::read(std::istream& stream)
{
        stream >> label >> type >> num >> x >> y >> z;
}
void INFO::mod_read(std::istream& stream)
{
        stream >> label >> type >> x >> y >> z;
}
double INFO::distance(INFO *i,double L)
{
        double delx = i->x - x - std::floor((i->x-x)/L + 0.5)*L;
        double dely = i->y - y - std::floor((i->y-y)/L + 0.5)*L;
        double delz = i->z - z - std::floor((i->z-z)/L + 0.5)*L;
        return delx*delx + dely*dely + delz*delz;
}
INFO::INFO(std::istream& stream)
{
        stream >> label >> type >> num >> x >> y >> z;
}

既然你的类包含了这些成员变量

std::string label, type;
unsigned int num;
double x, y, z, velx, vely, velz;
在复制构造函数中,复制引用对象中存在的值。因此,如下所示定义构造函数
INFO::INFO(const INFO &Ref)
{
    // copy the attributes
    this->label = Ref.label;
    this->type = Ref.type;
    this->num = Ref.num;
    this->x = Ref.x;
    this->y = Ref.y;
    this->z = Ref.z;
    this->velx = Ref.velx;
    this->vely = Ref.vely;
    this->velz = Ref.velz;
}

对于赋值操作符,您需要编写如下函数

INFO& INFO::operator= (const INFO &Ref)
{
    // copy the attributes
        this->label = Ref.label;
        this->type = Ref.type;
        this->num = Ref.num;
        this->x = Ref.x;
        this->y = Ref.y;
        this->z = Ref.z;
        this->velx = Ref.velx;
        this->vely = Ref.vely;
        this->velz = Ref.velz;
    // return the existing object
    return *this;
}

希望这是有效的,让我知道