定义复制构造函数和赋值操作符
defining copy constructor and assignment operator
这是我第一次用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;
}
希望这是有效的,让我知道
相关文章:
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 错误的数组初始化与赋值副本构造函数初始化
- 赋值复制构造函数
- 复制构造函数,赋值操作符重载
- 通过调用Move赋值操作符实现Move构造函数
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 类赋值操作符和复制构造函数
- 影响正确性的move构造函数/赋值操作符示例
- 如果没有定义Move语义(Move构造函数和Move赋值操作符),编译器是否默认优化
- 即使类没有定义构造函数,也不能在类上调用c++默认的move赋值操作符
- 复制构造函数和赋值操作符都被调用
- 与智能指针相关的c++移动语义与复制构造函数和赋值操作符
- 为什么不是只有一个?复制构造函数和赋值操作符
- c++析构函数、复制构造函数和赋值操作符实践考试
- 为什么这里需要构造函数和赋值操作符
- 赋值给构造函数中的常量变量
- 成员初始化列表vs赋值/复制构造函数(在boost deadline_timer中)
- 将传递的对象赋值给构造函数中的成员对象