good day! I study with ++ according to the book Stephen Prata wrote a class
#ifndef COW_H_ #define COW_H_ class Cow { private: char name[20]; char * hobby; double weight; public: Cow(); Cow(const char *nm, const char *ho, double wt); Cow(const Cow & c); ~Cow(); Cow & operator=(const Cow & c); void ShowCow() const; }; #endif class methods are as follows:
#include "cow.h" #include <iostream> #include <cstring> Cow::Cow() { strcpy(name, "NONE"); hobby = new char[5]; strcpy(hobby, "NONE"); weight = 0.0; } Cow::Cow(const char *nm, const char *ho, double wt) { if(nm == nullptr) { strcpy(name, "NONE"); } else { strncpy(name, nm, 19); name[19] = '\0'; } if(ho == nullptr) { hobby = new char[5]; strcpy(hobby, "NONE"); } else { int len = strlen(ho); hobby = new char[len+1]; strcpy(hobby, ho); } weight = wt; } Cow::Cow(const Cow & c) { strcpy(name, c.name); delete [] hobby; hobby = new char[strlen(c.hobby) + 1]; strcpy(hobby, c.hobby); weight = c.weight; } void Cow::ShowCow() const { std::cout << "Name: " << name << std::endl << "Hobby: " << hobby << std::endl << "Weight: " << weight << std::endl; } Cow::~Cow() { delete [] hobby; } Cow & Cow::operator=(const Cow & c) { if(this == &c) { return *this; } strcpy(name, c.name); delete [] hobby; hobby = new char[strlen(c.hobby) + 1]; strcpy(hobby, c.hobby); weight = c.weight; return *this; } a program is written to it:
#include <iostream> #include "cow.h" int main() { Cow one; Cow two("COwjsldnfsdn,sdnf,sndfsdmds","Music", 120.0); std::cout << "one: " << std::endl; one.ShowCow(); std::cout << "two:" << std::endl; two.ShowCow(); std::cout << "Three" << std::endl; Cow three = two; three.ShowCow(); three = two; three.ShowCow(); Cow four(one); std::cout << "Four = one:" << std::endl; four.ShowCow(); four = two; std::cout << "Four = two:" << std::endl; four.ShowCow(); return 0; } falls in the next line:
Cow three = two;
one: Name: NONE Hobby: NONE Weight: 0 two: Name: COwjsldnfsdn, sdnf, s Hobby: Music Weight: 120 Three Segmentation Error (memory dump made)
What I nakosyachil?