In the beginning of the program class cannot be assigned continuously, memory will be error. Debug a whole night to find out that the array n++ in new is an error. Both ++n and n+1 are tested to make the program work correctly.
n++ will error because n is used first, then n plus 1. And our expectation is to open an array of n+1 lengths instead of N, so we'll get an error.
In a single statement, there is no difference between the increment and the normal addition, but be careful in this compound statement and try not to use n++ and ++n
#pragmaOnce#ifndef Cow_h_#defineCow_h_classcow{Private://class default private,struct default public Charname[ -]; Char*Hobby; Doubleweight; Public: Cow (); Cow (Const Char* nm,Const Char* Ho,Doublewt); Cow (ConstCow &c); ~Cow (); Cow&operator=(ConstCow &c); voidShowcow ()Const;//Display all cow data};#endif // ! Cow_h_
cow.h
#include"Cow.h"#include<cstring>#include<iostream>usingstd::strcpy; Cow::cow () {name[0] =' /'; Hobby=New Char[1];//in order to unify the type of constructor, the destructor is compatiblehobby[0] =' /'; Weight=0;} Cow::cow (Const Char* nm,Const Char* Ho,Doublewt) {Weight=wt; strcpy (name, NM); intN; N=strlen (HO); Hobby=New Char[n+1];//Remember, add 1 .strcpy (Hobby, ho);} Cow::cow (ConstCow &c) {Weight=C.weight; strcpy (name, c.name); intN; N=strlen (C.hobby); Hobby=New Char[n+1]; strcpy (Hobby, c.hobby);} Cow::~Cow () {Delete[]hobby; Hobby=nullptr;}voidCow::showcow ()Const{ usingstd::cout; usingStd::endl; cout<< name <<Endl; cout<< Hobby <<Endl; cout<< Weight <<Endl;} Cow& Cow::operator=(ConstCow & C)//Remember to return{ //save memory by first deleting and then creating if( This= = &c)//Judging if it's self { return* This; } Delete[] hobby; strcpy (name, c.name); intN; N=strlen (C.hobby); Hobby=New Char[n+1]; strcpy (Hobby, c.hobby); Weight=C.weight; return* This;}//Continuous Assignment error reason is ++n!! //Never n++ in new, try to use less self-increment//++n and n+1 can, but n++ not, because new is the first new N,n plus 1, when the n++ self-increment operation is not but the statement, do not use, error-prone, like this type in parentheses
Cow.cpp
#include <iostream>#include<cstring>#include"Cow.h"usingstd::strcpy;usingstd::cin;usingstd::cout;usingStd::endl;intMain () {Cow milk ("a","Eat",56.9);//Cow::cow (const char *NM, const char *ho, double wt)Cow Junk ("T","C",200.66);//Cow::cow (const char *NM, const char *ho, double wt)milk. Showcow (); cout<<Endl; Cow M1;//Cow::cow ()M1 = milk;//Cow & cow::operator= (const COW & c)M1. Showcow (); cout<<Endl; Cow m2= junk;//Cow::cow (const COW & c), equivalent to M2 (junk)m2. Showcow (); cout<<Endl; Cow m3;//Cow::cow ()m3. Showcow (); cout<<Endl; M3= M1 = m2;//Cow & cow::operator= (const COW & c)//m3 = M1; //m3. Showcow (); //m3 = m2;m3. Showcow (); //Why is there an error in assigning two times? cout <<"OK"<<Endl; return 0;}
Test.cpp
C++primer plus 12th Chapter 1th of Programming question