c++ - 定义复制构造函数和赋值运算符

标签 c++ class corruption

<分区>

这是我第一次使用 C++ 处理类。我想知道是否有人可以帮助我为以下类正确设计复制构造函数和赋值运算符。

下面的帖子讲的是三分法则,

What is The Rule of Three?

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

信息.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

信息.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;
}

希望这个有用,让我知道

关于c++ - 定义复制构造函数和赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30758391/

相关文章:

c++ - 如何通过函数分配 std::string?

c++ - Armadillo ,如何增长 vector 并获得他的大小?

python - 仅限 Python 创建多项式类

mysql - MySQL 数据库损坏,只能通过 innodb_force_recovery=6 进行访问

c++ - C/C++ 如何查看当前机器上的域名?

c++ - 为什么 C++ 中的虚函数称为 'virtual' ?

java - 类对象与 HashMap

html - 滚动页面时导航栏从 anchor 添加删除类

.net - 故意破坏性能计数器注册表

java - 使用 java : corrupted data 从 FTP 站点下载文件