c++ - defining copy constructor and assignment operator -


this question has answer here:

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,

what rule of three?

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

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -