C++primer plus第六版课后编程题答案12.1
2014-04-19 23:42
465 查看
这里的delete[]应该改一下,改为delete,delete[]是对类似数组这种对象使用的,会对数组里面的每个对象调用一次析构函数,而delete则是对单个对象使用的。
-----------------2014.10.28
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Cow.h
Cow.cpp
main121.cpp
-----------------2014.10.28
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Cow.h
#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
Cow.cpp
#include <iostream> #include "Cow.h" //#include <string> #include <cctype> using namespace std; const int LIMIT=20; Cow::Cow() { strcpy(name,"default");//居然把strcpy写成了strcmp,我去啊 hobby=new char[LIMIT];//remember delete[] strcpy(hobby,"defaulthobby"); weight=0; cout<<"Cow() creat!"<<endl; } Cow::Cow(const char *nm,const char *ho,double wt) { //cout<<"first name is "<<name<<endl; strcpy(name,nm); //cout<<"now name is "<<name<<endl; hobby=new char[LIMIT];//remember delete[] //char *hobby=new char[LIMIT];//remember delete[] strcpy(hobby,ho); weight=wt; cout<<"Cow(const,const,wt) creat!"<<endl; } Cow::Cow(const Cow &c) { strcpy(name,c.name); hobby=new char[LIMIT]; strcpy(hobby,c.hobby); weight=c.weight; cout<<"Cow(Cow&) creat!"<<endl; } Cow::~Cow() { delete[]hobby; cout<<"Cow() destroy!"<<endl; } Cow& Cow::operator=(const Cow &c) { strcpy(name,c.name); delete []hobby;//记得删掉原来的 char *hobby=new char[LIMIT]; strcpy(hobby,c.hobby); weight=c.weight; return Cow(name,hobby,weight);//为何不能返回this?? } void Cow::showCow()const { cout<<"name:"<<name<<endl; cout<<"hobby:"<<hobby<<endl; cout<<"weight:"<<weight<<endl<<endl; }
main121.cpp
#include <iostream> #include "Cow.h" using namespace std; void main121() { { Cow c1; c1.showCow(); Cow c2("wawa","eat glassess",150); c2.showCow(); Cow c3=c2; c3.showCow(); Cow c4(c2); c4.showCow(); } cin.get(); }
相关文章推荐
- C++primer plus第六版课后编程题答案 6.4
- C++primer plus第六版课后编程题答案 6.9
- C++primer plus第六版课后编程题答案15.2
- C++primer plus第六版课后编程题答案16.9
- C++primer plus第六版课后编程题答案17.1
- C++primer plus第六版课后编程题答案17.3
- C++primer plus第六版课后编程题答案 6.4
- C++primer plus第六版课后编程题答案 6.6
- C++primer plus第六版课后编程题答案7.4
- C++primer plus第六版课后编程题答案 7.7
- C++primer plus第六版课后编程题答案8.5
- C++primer plus第六版课后编程题答案12.2
- C++primer plus第六版课后编程题答案14.4
- C++primer plus第六版课后编程题答案14.5
- C++primer plus第六版课后编程题答案15.4
- C++primer plus第六版课后编程题答案16.6
- C++primer plus第六版课后编程题答案16.7
- C++primer plus第六版课后编程题答案17.4
- 关于“C++primer plus第六版课后编程题答案”18章的说明
- C++primer plus第六版课后编程题答案 6.1