这是我第一次使用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;
}
答案 0 :(得分:2)
由于您的类包含这些成员变量
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;
}
希望这有效,让我知道