c++ - defining copy constructor and assignment operator -
this question has answer here:
- what rule of three? 8 answers
it's first time dealing classes in c++. wondering if me design copy constructor , assignment operator following class.
the following post talks rule of threes,
although, not clear how implement code.
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; }
since class contains these member variables
std::string label, type; unsigned int num; double x, y, z, velx, vely, velz;
in copy constructor copy values present in reference object. so, define constructor below
info::info(const info &ref) { // copy 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; }
for assignment operator need write function
info& info::operator= (const info &ref) { // copy 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 existing object return *this; }
hope works, let me know
Comments
Post a Comment