C++Primer 第15章-面向对象编程-课后习题答案

合集下载

面向对象的C++程序设计 第六版 课后习题答案 第十五章

面向对象的C++程序设计 第六版 课后习题答案 第十五章

Chapter15INHERITANCE1.Solutions to and Remarks on Selected Programming Problems1.Derive class Administrator from class SalariedEmployeePlease note an error in the statement of Programming Project1:In the requirement for a member function called"print"which the problem says"...output the programmer's data to the screen."This should read"...output the administrator's data to the screen."Remarks:Ideally the member functions in the base class Employee that are going to be declared in derived classes should be declared"pure virtual"where the body{...}is replaced by=0;. This results in the compiler forcing any directly derived function to define a member with this signature,which,presumably is better suited than any base class member function will be.Print check may well be different for each derived class.The member function void give_raise(double)could be different as well.Regarding the function that reads the administrator's data,note that a new administrator's data will be entered in response to the base class Employee and derive class SalariedEmployee inquiries,then the administrator class function will make inquiry.My design and implementation follow:Title:Derive class AdministratorWrite a program using classes from Display15.1-15.4Define class Administrator which derives publicly from class SalariedEmployee. Explain why there is a need to change private:to protected:Answer:To allow the member functions inherited class member to see these data members.Additional protected members required are:string titleadministrator's title(CEO,Director etc.)string responsibility(production,accounting,personnel) string supervisor(name of immediate supervisor)double annual_salary(if not already added in the self test exercise)Additional public members required are:A function to change name of immediate supervisorvoid change_supervisor(string new_super);A function for reading all of a new administrator's data from the keyboard.Note that the data inherited from class Employee will already be fetched by required base class constructors.class constructors.void get_admin_data();function to output administrator's data to the screenvoid print();a function to print a check with appropriate notations on the checkvoid print_check()//file:ch15p1.h//This is the INTERFACE for class Administrator which//inherits from class Employee and class SalariedEmployee#ifndef ADMINISTRATOR_H#define ADMINISTRATOR_H#include"employee.h"//from Display15.1 namespace employeessavitch{class Administrator:public SalariedEmployee{public:Administrator();Administrator(string aTitle,string aResponsibilty,string aSupervisor);//change name of immediate supervisorvoid change_supervisor(string new_super);//Read a new administrator's data from the keyboard.void get_admin_data();//outputs administrator's data to the screenvoid print();//prints a check with appropriate notations on the checkvoid print_check();void give_raise(double amount);protected:string title;//administrator's title//(CEO,Director,Vice President)string responsibility;//production,accounting, personnelstring supervisor;//name of immediate supervisor long double annual_salary;//if not added in the self//test exercise};}#endif//File://Chapter15Programming Project1//Implementation for the Administrator derived class#include"employee.h"//display15.2#include"ch15p1.h"//Previous header file#include<iostream>namespace employeesavitch{voidAdministrator::give_raise(double amount){annual_salary+=amount;}Administrator::Administrator():SalariedEmployee(){using namespace std;cout<<"\nAdministrative Employee data"<<"is being entered:\n\n";get_admin_data();}Administrator::Administrator(string aTitle,string aResponsibilty,string aSupervisor):SalariedEmployee(),title(aTitle),responsibility(aResponsibilty),supervisor(aSupervisor){//deliberately empty}//change name of immediate supervisorvoid Administrator::change_supervisor(string new_super) {supervisor=new_super;}//Reading all of a new administrator's data from the//keyboard.void Administrator::get_admin_data(){using namespace std;cout<<"Enter title,followed by return:\n";getline(cin,title);cout<<"\nEnter area of responsibility"<<"followed by return:\n";getline(cin,responsibility);cout<<"\nEnter supervisor's name,"<<"followed by return:\n";getline(cin,supervisor);cout<<"\nEnter salary followed by return:\n";cin>>annual_salary;}//outputs administrator's data to the screenvoid Administrator::print(){using namespace std;cout<<"\n\nprinting data\n";cout<<"Name:"<<name<<endl;cout<<"Annual Salary:$"<<annual_salary<<endl; cout<<"Social Security Number:"<<ssn<<endl; cout<<"Title:";cout<<title<<endl;cout<<"Responsibility:";cout<<responsibility<<endl;cout<<"supervisor:";cout<<supervisor<<endl;cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);cout<<"Annual Salary:";cout<<annual_salary<<endl;}//prints a check with appropriate notations on the check void Administrator::print_check(){using namespace std;long double monthly_pay=annual_salary/12;cout<<"\n__________________________________________________\n"; cout<<"Pay to the order of"<<name<<endl;cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);cout<<"The sum of$"<<monthly_pay<<"Dollars\n";cout<<"_________________________________________________\n";cout<<"Check Stub NOT NEGOTIABLE\n";cout<<"Employee Number:"<<ssn<<endl;cout<<"Administrative Employee.\n";cout<<"_________________________________________________\n"; }}//end namespace employeesavitch2.Add Temporary,Administrative,Permenant etc classifications to15.1…No solution is provided for this problem.3.Derive class Doctor from SalariedEmployeeNo solution is provided for this problem.4.Create a base class vehicleNo solution is provided for this problem.5.Define classes Patient and BillingNo solution is provided for this problem.6.No Solution Provided.7.Implement a graphics SystemImplement a graphics System that has classes for various figures:rectangles,squares, triangles,circles,etc.A rectangle has data members height,width,and center point.A square has center point and an edge.A circle has data members center and radius.The several specific shape classes are derived from a common class,Figure. Implement only Rectangle and Triangle classes.Derive them from Figure. Each class has stubs for erase and draw.The class Figure has member function center that calls erase and draw.The functions erase and draw are only stubs,consequently center does little but call erase and draw.Add a message to center announcing that it is being called.There are3parts:a)Write the class definitions using no virtual pile and test.b)Make the base class member functions pile and test.c)Explain the differences.Use the following main function:#include<iostream>#include"figure.h"#include"rectangle.h"#include"triangle.h"using std::cout;int main(){Triangle tri;tri.draw();cout<<"\nDerived class Triangle object calling"<<"center().\n";tri.center();Rectangle rect;rect.draw();cout<<"\nDerived class Rectangle object calling"<<"center().\n";rect.center();return0;}Solution:I have used no member variables,as they serve no function in this part of the exercise.//figure.h#include<iostream>using namespace std;#ifndef PROTECT_FIGURE_H#define PROTECT_FIGURE_Hclass Figure{public://virtual//Uncomment to make erase()a virtual function void erase();//virtual//Uncomment to make draw()a virtual function void draw();void center(){cout<<"member function center called"<<endl;erase();draw();}};#endif//File:figure.cpp#include"figure.h"void Figure::erase(){cout<<"Figure::erase()"<<endl; }void Figure::draw(){cout<<"Figure::draw()"<<endl; }//end of file figure.cpp//rectangle.h#include<iostream>#include"figure.h"using namespace std;class Rectangle:public Figure{public:void erase();void draw();};void Rectangle::erase(){cout<<"Rectangle::erase()"<<endl; }void Rectangle::draw(){cout<<"Rectangle::draw()"<<endl; }//triangle.h#include<iostream>#include"figure.h"using namespace std;class Triangle:public Figure{public:void draw();void erase();};void Triangle::draw(){cout<<"Triangle::draw()"<<endl; }void Triangle::erase(){cout<<"Triangle::erase()"<<endl;}//ch13p1App.cpp#include<iostream>#include"figure.h"#include"rectangle.h"#include"triangle.h"using std::cout;int main(){Triangle tri;tri.draw();cout<<"\nIn main,Derived class Triangle object calling"<<"center().\n";tri.center();Rectangle rect;rect.draw();cout<<"\nIn main,Derived class Rectangle object calling"<<"center().\n";rect.center();return0;}A trial run follows:With NON virtual draw()and erase()Triangle::draw()In main,Derived class Triangle object calling center(). member function center calledFigure::erase()Figure::draw()Rectangle::draw()In main,Derived class Rectangle object calling center(). member function center calledFigure::erase()Figure::draw()With virtual draw()and erase():Triangle::draw()In main,Derived class Triangle object calling center(). member function center calledTriangle::erase()Triangle::draw()Rectangle::draw()Explanation of differenceThe differences are due solely to the presence or absence of the keyword virtual in the base class figure.8.Flesh out Problem7Give new definitions and member functions for Figure::center,Figure::draw, Figure::erase,Triangle::draw,Triangle::erase, Rectangle::draw,Rectangle::erase,so that the draw functions actually draw figures on the screen using asterisks(*).For the erase function,clear the screen.No solution to this part is provided.9.No Solution Provided.10.//****************************************************************////Ch15Proj10.cpp////This program uses inheritance to simulate retrieving the contents //of a RFID shipping container and a manual shipping container.//****************************************************************#include<iostream>#include<vector>#include<string>#include<sstream>using namespace std;//*************************Begin ShippingContainer Classclass ShippingContainer{public:ShippingContainer();ShippingContainer(int newID);int getID();void setID(int newID);virtual string getManifest();private:int id;};//======================//ShippingContainer::ShippingContainer//Constructors//======================ShippingContainer::ShippingContainer(){id=-1;}ShippingContainer::ShippingContainer(int newID){id=newID;}//======================//ShippingContainer::getID//Returns the ID number//======================int ShippingContainer::getID(){return id;}//======================//ShippingContainer::setID//Sets the ID number//======================void ShippingContainer::setID(int newID){id=newID;}//======================//ShippingContainer::getManifest//Returns empty contents//======================string ShippingContainer::getManifest(){return"";}//*************************Begin ManualShippingContainer Classclass ManualShippingContainer:public ShippingContainer{public:ManualShippingContainer(int newID);void setManifest(string s);virtual string getManifest();private:string contents;};//======================//ManualShippingContainer::ManualShippingContainer//Constructor//====================== ManualShippingContainer::ManualShippingContainer(int newID): ShippingContainer(newID){}//======================//ManualShippingContainer::setManifest//Sets the manifest for this container//======================void ManualShippingContainer::setManifest(string s){contents=s;}//======================//ManualShippingContainer::getManifest//Returns the manifest for this container//======================string ManualShippingContainer::getManifest(){return contents;}//*************************Begin RFIDShippingContainer Classclass RFIDShippingContainer:public ShippingContainer{public:RFIDShippingContainer(int newID);void add(string s);virtual string getManifest();private:vector<string>contents;vector<int>count;int search(string s);};//======================//RFIDShippingContainer::RFIDShippingContainer//Constructor//======================RFIDShippingContainer::RFIDShippingContainer(int newID):ShippingContainer(newID){}//======================//RFIDShippingContainer::search//Search the vector for duplicates and if found//returns the index,or-1if not found//======================int RFIDShippingContainer::search(string s){int i;for(i=0;i<contents.size();i++){if(contents[i]==s)return i;}return-1;}//======================//RFIDShippingContainer::add//Adds a new string to the manifest vector.//======================void RFIDShippingContainer::add(string s){int i;i=search(s);if(i==-1){contents.push_back(s);//Add itemcount.push_back(1);//One occurrence of this item }else{count[i]++;//Add to occurrences of this item }}//======================//RFIDShippingContainer::getManifest//Returns the manifest for this container//by scanning through the vector//======================string RFIDShippingContainer::getManifest(){string s="";int i;for(i=0;i<contents.size();i++){//Convert number to string using stringstreamstringstream converter;converter<<count[i];s+=converter.str()+""+contents[i]+".";}return s;}//======================//main function//======================int main(){//Variable declarations with test data ShippingContainer*containers[6]; ManualShippingContainer m1(100),m2(200),m3(300); RFIDShippingContainer r1(400),r2(500),r3(600);m1.setManifest("1000diapers");m2.setManifest("1000candy bars.500toilet paper.");m3.setManifest("500books.");r1.add("apples");r1.add("apples");r1.add("cookies");r2.add("pineapple");r2.add("pears");r2.add("pineapple");r2.add("pears");r3.add("chocolate bars");r3.add("chocolate bars");r3.add("chocolate bars");//Store containers in the arraycontainers[0]=&m1;containers[1]=&m2;containers[2]=&m3;containers[3]=&r1;containers[4]=&r2;containers[5]=&r3;//Loop to output contents of the containersfor(int i=0;i<6;i++){cout<<"Container"<<containers[i]->getID()<<"contains"<<containers[i]->getManifest()<<endl; }return0;}11.//**************************************************************** ////Ch15Proj11.cpp////This program simulates a2D world with predators and prey.//The predators(doodlebugs)and prey(ants)inherit from the//Organism class that keeps track of basic information about each //critter(time ticks since last bred,position in the world).////The2D world is implemented as a separate class,World,//that contains a2D array of pointers to type Organism.////Normally the classes would be defined in separate files,but//they are all included here for ease of use with CodeMate.//****************************************************************#include<iostream>#include<string>#include<vector>#include<cstdlib>#include<time.h>using namespace std;const int WORLDSIZE=20;const int INITIALANTS=100;const int INITIALBUGS=5;const int DOODLEBUG=1;const int ANT=2;const int ANTBREED=3;const int DOODLEBREED=8;const int DOODLESTARVE=3;//Forward declaration of Organism classes so we can reference it//in the World classclass Organism;class Doodlebug;class Ant;//==========================================//The World class stores data about the world by creating a//WORLDSIZE by WORLDSIZE array of type Organism.//NULL indicates an empty spot,otherwise a valid object//indicates an ant or doodlebug.To determine which,//invoke the virtual function getType of Organism that should return //ANT if the class is of type ant,and DOODLEBUG otherwise.//==========================================class World{friend class Organism;//Allow Organism to access grid friend class Doodlebug;//Allow Organism to access grid friend class Ant;//Allow Organism to access grid public:World();~World();Organism*getAt(int x,int y);void setAt(int x,int y,Organism*org);void Display();void SimulateOneStep();private:Organism*grid[WORLDSIZE][WORLDSIZE];};//==========================================//Definition for the Organism base class.//Each organism has a reference back to//the World object so it can move itself//about in the world.//==========================================class Organism{friend class World;//Allow world to affect organism public:Organism();Organism(World*world,int x,int y);~Organism();virtual void breed()=0;//Whether or not to breedvirtual void move()=0;//Rules to move the crittervirtual int getType()=0;//Return if ant or doodlebugvirtual bool starve()=0;//Determine if organism starves protected:int x,y;//Position in the worldbool moved;//Bool to indicate if moved this turnint breedTicks;//Number of ticks since breeding World*world;};//======================//World constructor,destructor//These classes initialize the array and//releases any classes created when destroyed.//======================World::World(){//Initialize world to empty spacesint i,j;for(i=0;i<WORLDSIZE;i++){for(j=0;j<WORLDSIZE;j++){grid[i][j]=NULL;}}}World::~World(){//Release any allocated memoryint i,j;for(i=0;i<WORLDSIZE;i++){for(j=0;j<WORLDSIZE;j++){if(grid[i][j]!=NULL)delete(grid[i][j]);}}}//======================//getAt//Returns the entry stored in the grid array at x,y//======================Organism*World::getAt(int x,int y){if((x>=0)&&(x<WORLDSIZE)&&(y>=0)&&(y<WORLDSIZE)) return grid[x][y];return NULL;}//======================//setAt//Sets the entry at x,y to the//value passed in.Assumes that//someone else is keeping track of//references in case we overwrite something//that is not NULL(so we don't have a memory leak)//======================void World::setAt(int x,int y,Organism*org){if((x>=0)&&(x<WORLDSIZE)&&(y>=0)&&(y<WORLDSIZE)){grid[x][y]=org;}}//======================//Display//Displays the world in es o for ant,X for doodlebug. //======================void World::Display(){int i,j;cout<<endl<<endl;for(j=0;j<WORLDSIZE;j++){for(i=0;i<WORLDSIZE;i++){if(grid[i][j]==NULL)cout<<".";else if(grid[i][j]->getType()==ANT)cout<<"o";else cout<<"X";}cout<<endl;}}//======================//SimulateOneStep//This is the main routine that simulates one turn in the world.//First,a flag for each organism is used to indicate if it has moved. //This is because we iterate through the grid starting from the top//looking for an organism to move.If one moves down,we don't want//to move it again when we reach it.//First move doodlebugs,then ants,and if they are still alive then//we breed them.//======================void World::SimulateOneStep(){int i,j;//First reset all organisms to not movedfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){if(grid[i][j]!=NULL)grid[i][j]->moved=false;}//Loop through cells in order and move if it's a Doodlebugfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){if((grid[i][j]!=NULL)&&(grid[i][j]->getType()==DOODLEBUG)){if(grid[i][j]->moved==false){grid[i][j]->moved=true;//Mark as movedgrid[i][j]->move();}}}//Loop through cells in order and move if it's an Antfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){if((grid[i][j]!=NULL)&&(grid[i][j]->getType()==ANT)){if(grid[i][j]->moved==false){grid[i][j]->moved=true;//Mark as movedgrid[i][j]->move();}}}//Loop through cells in order and check if we should breedfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){//Kill off any doodlebugs that haven't eaten recentlyif((grid[i][j]!=NULL)&&(grid[i][j]->getType()==DOODLEBUG)){if(grid[i][j]->starve()){delete(grid[i][j]);grid[i][j]=NULL;}}}//Loop through cells in order and check if we should breedfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){//Only breed organisms that have moved,since//breeding places new organisms on the map we//don't want to try and breed thoseif((grid[i][j]!=NULL)&&(grid[i][j]->moved==true)){grid[i][j]->breed();}}}//======================//Organism Constructor//Sets a reference back to the World object.//======================Organism::Organism(){world=NULL;moved=false;breedTicks=0;x=0;y=0;}Organism::Organism(World*wrld,int x,int y){this->world=wrld;moved=false;breedTicks=0;this->x=x;this->y=y;wrld->setAt(x,y,this);}//======================//Organism destructor//No need to delete the world reference,//it will be destroyed elsewhere.//======================Organism::~Organism(){}//Start with the Ant classclass Ant:public Organism{friend class World;public:Ant();Ant(World*world,int x,int y);void breed();//Must define this since virtualvoid move();//Must define this since virtualint getType();//Must define this since virtualbool starve()//Return false,ant never starves{return false;}};//======================//Ant constructor//======================Ant::Ant():Organism(){}Ant::Ant(World*world,int x,int y):Organism(world,x,y) {}//======================//Ant Move//Look for an empty cell up,right,left,or down and//try to move there.//======================void Ant::move(){//Pick random direction to moveint dir=rand()%4;//Try to move up,if not at an edge and empty spotif(dir==0){if((y>0)&&(world->getAt(x,y-1)==NULL)){world->setAt(x,y-1,world->getAt(x,y));//Move to new spotworld->setAt(x,y,NULL);y--;}}//Try to move downelse if(dir==1){if((y<WORLDSIZE-1)&&(world->getAt(x,y+1)==NULL)){world->setAt(x,y+1,world->getAt(x,y));//Move to new spotworld->setAt(x,y,NULL);//Set current spot to emptyy++;}}//Try to move leftelse if(dir==2){if((x>0)&&(world->getAt(x-1,y)==NULL)){world->setAt(x-1,y,world->getAt(x,y));//Move to new spotworld->setAt(x,y,NULL);//Set current spot to emptyx--;}}//Try to move rightelse{if((x<WORLDSIZE-1)&&(world->getAt(x+1,y)==NULL)){world->setAt(x+1,y,world->getAt(x,y));//Move to new spotworld->setAt(x,y,NULL);//Set current spot to emptyx++;}}}//======================//Ant getType//This virtual function is used so we can determine//what type of organism we are dealing with.//======================int Ant::getType(){return ANT;}//======================//Ant breed//Increment the tick count for breeding.//If it equals our threshold,then clone this ant either//above,right,left,or below the current one.//======================void Ant::breed(){breedTicks++;if(breedTicks==ANTBREED){breedTicks=0;//Try to make a new ant either above,left,right,or downif((y>0)&&(world->getAt(x,y-1)==NULL)){Ant*newAnt=new Ant(world,x,y-1);}else if((y<WORLDSIZE-1)&&(world->getAt(x,y+1)==NULL)){Ant*newAnt=new Ant(world,x,y+1);}else if((x>0)&&(world->getAt(x-1,y)==NULL)){Ant*newAnt=new Ant(world,x-1,y);}else if((x<WORLDSIZE-1)&&(world->getAt(x+1,y)==NULL)){Ant*newAnt=new Ant(world,x+1,y);}}}//*****************************************************//Now define Doodlebug Class//*****************************************************class Doodlebug:public Organism{friend class World;public:Doodlebug();Doodlebug(World*world,int x,int y);void breed();//Must define this since virtualvoid move();//Must define this since virtualint getType();//Must define this since virtualbool starve();//Check if a doodlebug starves to deathprivate:int starveTicks;//Number of moves before starving};//======================//Doodlebug constructor//======================Doodlebug::Doodlebug():Organism(){starveTicks=0;}Doodlebug::Doodlebug(World*world,int x,int y):Organism(world,x,y) {starveTicks=0;}//======================//Doodlebug move//Look up,down,left or right for a bug.If one is found,move there //and eat it,resetting the starveTicks counter.//======================void Doodlebug::move(){//Look in each direction and if a bug is found move there//and eat it.if((y>0)&&(world->getAt(x,y-1)!=NULL)&&(world->getAt(x,y-1)->getType()==ANT)){delete(world->grid[x][y-1]);//Kill antworld->grid[x][y-1]=this;//Move to spotworld->setAt(x,y,NULL);starveTicks=0;//Reset hungery--;return;}else if((y<WORLDSIZE-1)&&(world->getAt(x,y+1)!=NULL)&&(world->getAt(x,y+1)->getType()==ANT)){delete(world->grid[x][y+1]);//Kill antworld->grid[x][y+1]=this;//Move to spotworld->setAt(x,y,NULL);starveTicks=0;//Reset hungery++;return;}else if((x>0)&&(world->getAt(x-1,y)!=NULL)&&(world->getAt(x-1,y)->getType()==ANT)){delete(world->grid[x-1][y]);//Kill antworld->grid[x-1][y]=this;//Move to spot。

面向对象技术(C++ Primer)第15章

面向对象技术(C++ Primer)第15章

Virtual和其他成员函数
15
要触发动态绑定,必须满足两个条件:只 有指定为虚函数的成员才能进行动态绑定 。成员函数默认为非虚函数,非虚函数不 能进行动态绑定。必须通过基类类型的引 用或指针进行调用。
从派生类到基类的转换 16
Double print_total(const Item_base&, size_t); Item_base item; //object of base type Print_total(item,10); //passes reference to an Item_base object Item_base *p=&item; //p points to an Item_base object Bulk_item bulk; //object of derived type Print_total(bulk,10); //passes reference to the item_base part of bulk P=&bulk; //p points to the item_base part of bulk
已定义的类才可用作基类。如果已声明 Item_base,但没有定义它,则不能用作基 类。这是因为,每个派生类中包含并且可 以访问其基类的成员。为了使用这些成员 派生类必须知道它们是什么。这一规则暗 示着不可能从类自身派生出一个类。 基类本身也可以是一个派生类。 Class Base{}; Class D1:public Base{}; Class D2:public D1{};
3
std::string book() const { return isbn; } virtual double net_price(std::size_t n) const { return n * price; } // no work, but virtual destructor needed if base pointer that points to a derived object is ever deleted virtual ~Item_base() { } private: std::string isbn; // identifier for the item protected: double price; // normal, undiscounted price };

c--面向对象程序设计课后习题解答-谭浩强

c--面向对象程序设计课后习题解答-谭浩强

第1章C++ 的初步知识1.请根据你的了解,叙述C++的特点。

C++对C有哪些发展?【解】略。

2.一个C++的程序是由哪几部分构成的?其中的每一部分起什么作用?【解】略。

3.从拿到一个任务到得到最终结果,一般要经过几个步骤?【解】略.4.请说明编辑、编译、连接的作用。

在编译后得到的目标文件为什么不能直接运行?【解】编译是以源程序文件为单位进行的,而一个完整的程序可能包含若干个程序文件,在分别对它们编译之后,得到若干个目标文件(后缀一般为.obj),然后要将它们连接为一个整体.此外,还需要与编译系统提供的标准库相连接,才能生成一个可执行文件(后缀为。

exe)。

不能直接运行后缀为。

obj的目标文件,只能运行后缀为。

exe的可执行文件.5.分析下面程序运行的结果。

#includeusing namespace std;int main({cout<<” This "<〈” is ";cout〈<” a "<<” C++”;cout〈〈”program。

” <〈 endl;return 0;}【解】输出的结果为Thisisa C++program。

6.分析下面程序运行的结果。

#includeusing namespace std;int main({int a,b,c;a=10;b=23;c=a+b;cout〈〈” a+b=”;cout<cout<return 0;}【解】前两个cout语句在输出数据后不换行,第3个cout语句输出一个换行,因此输出的结果为a+b=337.分析下面程序运行的结果.请先阅读程序写出程序运行时应输出的结果,然后上机运行程序,验证自己分析的结果是否正确.以下各题同。

#includeusing namespace std;int main({int a,b,c;int f(int x,int y,int z;cin〉>a〉〉b>>c;c=f(a,b,c;cout<}int f(int x,int y,int z{int m;if (xelse m=y;if (zreturn(m;}【解】程序的作用是:输入3个整数,然后输出其中值最小的数。

面向对象程序设计课后答案完整版

面向对象程序设计课后答案完整版

第二章2-4#include <iostream>using namespace std;Add(int a,int b);int main(){int x,y,sum;cout<<"please input x and y:";cin>>x>>y;sum = add(x,y);cout <<x<<"+"<<y<<"="<<sum<<endl;}Add(int a,int b){return a+b;}2-5(1)this is a C++ program.(2)x=50.6 y=10 z=Ax=216.34 y=10 z=Ax=216.34 y=2 z=Ax=216.34 y=2 z=E(3)x y z500 1000 0500 1500 1500500 200 15002-6#include <iostream>using namespace std;int main(){int *p,*init;int countp=0;int countn=0;p = new int[20];init = p;for(int i=0;i<20;i++){cin>>*p;p++;}p = p-20;for( i=0;i<20;i++){if(*p>0) countp++;if(*p<0) countn++;cout<<*p<<" ";p++;}cout<<"正数有:"<<countp<<endl; cout<<"负数有:"<<countn<<endl;p = init;delete[] p;return 0;}2-7不做要求#include <iostream>//#include <string>using namespace std;void checkagescore(string name,int age) {if (name == "exit") throw name;if(age<0||age>50)throw age;int main(){string name;int age;for(int i=0 ;i<5 ;i++ ){cin.ignore ();getline(cin,name );cin>>age ;try{checkagescore(name,age);}catch( string){cout<<"exception :name is exit"<<endl;continue;}catch(int){cout<<"exception :age is not proper"<<endl;continue;}cout<<"name:"<<name<<" age :"<<age<<endl;}return 0;}第三章3-1(1)A (2)C (3)B (4)C (5)C(6)B (7)B (8)C (9)C3-7(1)main()函数中p1.age = 30;语句是错误的。

面向对象程序设计C课后题答案

面向对象程序设计C课后题答案

第一章:面向对象程序设计概述[1_1]什么是面向对象程序设计?面向对象程序设计是一种新型的程序设计范型。

这种范型的主要特征是:程序=对象+消息。

面向对象程序的基本元素是对象,面向对象程序的主要结构特点是:第一:程序一般由类的定义和类的使用两部分组成,在主程序中定义各对象并规定它们之间传递消息的规律。

第二:程序中的一切操作都是通过向对象发送消息来实现的,对象接受到消息后,启动有关方法完成相应的操作。

面向对象程序设计方法模拟人类习惯的解题方法,代表了计算机程序设计新颖的思维方式。

这种方法的提出是软件开发方法的一场革命,是目前解决软件开发面临困难的最有希望、最有前途的方法之一。

[1_2]什么是类?什么是对象?对象与类的关系是什么?在面向对象程序设计中,对象是描述其属性的数据以及对这些数据施加的一组操作封装在一起构成的统一体。

对象可以认为是:数据+操作在面向对象程序设计中,类就是具有相同的数据和相同的操作的一组对象的集合,也就是说,类是对具有相同数据结构和相同操作的一类对象的描述。

类和对象之间的关系是抽象和具体的关系。

类是多个对象进行综合抽象的结果,一个对象是类的一个实例。

在面向对象程序设计中,总是先声明类,再由类生成对象。

类是建立对象的“摸板”,按照这个摸板所建立的一个个具体的对象,就是类的实际例子,通常称为实例。

[1_3]现实世界中的对象有哪些特征?请举例说明。

对象是现实世界中的一个实体,其具有以下一些特征:(1)每一个对象必须有一个名字以区别于其他对象。

(2)需要用属性来描述它的某些特性。

(3)有一组操作,每一个操作决定了对象的一种行为。

(4)对象的操作可以分为两类:一类是自身所承受的操作,一类是施加于其他对象的操作。

例如:雇员刘名是一个对象对象名:刘名对象的属性:年龄:36 生日:1966.10.1 工资:2000 部门:人事部对象的操作:吃饭开车[1_4]什么是消息?消息具有什么性质?在面向对象程序设计中,一个对象向另一个对象发出的请求被称为“消息”。

c++面向对象程序设计课后习题答案

c++面向对象程序设计课后习题答案

第一章5:#include <iostream>using namespace std;int main(){cout<<"This"<<"is";cout<<"a"<<"C++";cout<<"program."<<endl; return 0;}6:#include <iostream>using namespace std;int main(){int a,b,c;a=10;b=23;c=a+b;cout<<"a+b=";cout<<c;cout<<endl;return 0;}7:#include <iostream>using namespace std;int main(){int a,b,c;int f(int x,int y,int z); cin>>a>>b>>c;c=f(a,b,c);cout<<c<<endl;return 0;}int f(int x,int y,int z) {int m;if (x<y) m=x;else m=y;if (z<m) m=z;return(m);}8: #include <iostream>using namespace std;int main(){int a,b,c;cin>>a>>b;c=a+b;cout<<"a+b="<<a+b<<endl;return 0;}9:#include <iostream>using namespace std;int main(){int add(int x,int y);int a,b,c;cin>>a>>b;c=add(a,b);cout<<"a+b="<<c<<endl;return 0;}int add(int x,int y){int c;c=x+y;return(c);}10:#include <iostream>using namespace std;int main(){void sort(int x,int y,int z); int x,y,z;cin>>x>>y>>z;sort(x,y,z);return 0;}void sort(int x, int y, int z){int temp;if (x>y) {temp=x;x=y;y=temp;} 2-4-12-4-22-5-12-5-2Box box1Box box1core; int k=0;for(int i=1;i<5;i++)if(arr[i].score>max_score) {max_score=arr[i].score;k=i;}cout<<arr[k].num<<" "<<max_score<<endl;}6:#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) {num=n;score=s;}void display(){cout<<num<<" "<<score<<endl;}private:int num;float score;};int main(){Student stud(101,;();(101,;();return 0;}7: 解法一#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) {num=n;score=s;}void display() {cout<<num<<" "<<score<<endl;}otal();Product::display();return 0;}10:#include <iostream>using namespace std;class Date;class Time{public:Time(int,int,int);friend void display(const Date &,const Time &); private:int hour;int minute;int sec;};Time::Time(int h,int m,int s){hour=h;minute=m;sec=s;}class Date{public:Date(int,int,int);friend void display(const Date &,const Time &); private:int month;int day;int year;};Date::Date(int m,int d,int y){month=m;day=d;year=y;}void display(const Date &d,const Time &t){cout<<<<"/"<<<<"/"<<<<endl;cout<<<<":"<<<<":"<<<<endl;int main(){Time t1(10,13,56);Date d1(12,25,2004);display(d1,t1);return 0;}11:#include <iostream>using namespace std;class Time;class Date{public:Date(int,int,int);friend Time;private:int month;int day;int year;};Date::Date(int m,int d,int y):month(m),day(d),year(y){ }class Time{public:Time(int,int,int);void display(const Date &);private:int hour;int minute;int sec;};Time::Time(int h,int m,int s):hour(h),minute(m),sec(s){ }void Time::display(const Date &d){cout<<<<"/"<<<<"/"<<<<endl;cout<<hour<<":"<<minute<<":"<<sec<<endl;}int main(){Time t1(10,13,56);Date d1(12,25,2004);(d1);return 0;}12:#include <iostream>using namespace std;template<class numtype>class Compare{public:Compare(numtype a,numtype b);numtype max();numtype min();private:numtype x,y;};template <class numtype>Compare<numtype>::Compare(numtype a,numtype b){x=a;y=b;}template <class numtype>numtype Compare<numtype>::max(){return (x>y)x:y;}template <class numtype>numtype Compare<numtype>::min(){return (x<y)x:y;}int main(){Compare<int> cmp1(3,7);cout<<()<<" is the Maximum of two integer numbers."<<endl;cout<<()<<" is the Minimum of two integer numbers."<<endl<<endl; Compare<float> cmp2,;cout<<()<<" is the Maximum of two float numbers."<<endl;cout<<()<<" is the Minimum of two float numbers."<<endl<<endl;Compare<char> cmp3('a','A');cout<<()<<" is the Maximum of two characters."<<endl;cout<<()<<" is the Minimum of two characters."<<endl;return 0;}第四章1:#include <iostream>using namespace std;class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;} double get_real();double get_imag();void display();private:double real;double imag;};double Complex::get_real(){return real;}double Complex::get_imag(){return imag;}void Complex::display(){cout<<"("<<real<<","<<imag<<"i)"<<endl;}Complex operator + (Complex &c1,Complex &c2) {return Complex()+(),()+());}int main(){Complex c1(3,4),c2(5,-10),c3;c3=c1+c2;cout<<"c3=";();return 0;}2:#include <iostream>using namespace std;class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;} Complex operator+(Complex &c2);Complex operator-(Complex &c2);Complex operator*(Complex &c2);Complex operator/(Complex &c2);void display();private:double real;double imag;};Complex Complex::operator+(Complex &c2) {Complex c;=real+;=imag+;return c;}Complex Complex::operator-(Complex &c2) {Complex c;=;=;return c;}Complex Complex::operator*(Complex &c2) {Complex c;=real**;=imag*+real*;return c;}Complex Complex::operator/(Complex &c2) {Complex c;=(real*+imag*/*+*;=(imag**/*+*;return c;}void Complex::display(){cout<<"("<<real<<","<<imag<<"i)"<<endl;}int main(){Complex c1(3,4),c2(5,-10),c3;c3=c1+c2;cout<<"c1+c2=";();c3=c1-c2;cout<<"c1-c2=";();c3=c1*c2;cout<<"c1*c2=";();c3=c1/c2;cout<<"c1/c2=";();return 0;}3:#include <iostream> ,"president","135 Beijing Road,Shanghai","(021)",;( );return 0;}10:#include <iostream>#include <cstring>using namespace std;class Teacher um<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;((char *)&staf[i],sizeof(staf[i]));}cout<<"please input data you want insert:"<<endl;for(i=0;i<2;i++){cin>>>>>>>>;(0,ios::end);((char *)&staf1,sizeof(staf1));}(0,ios::beg);for(i=0;i<7;i++){((char *)&staf[i],sizeof(staf[i]));cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;}bool find;cout<<"enter number you want search,enter 0 to stop.";cin>>num;while(num){find=false;(0,ios::beg);for(i=0;i<7;i++){((char *)&staf[i],sizeof(staf[i]));if(num==staf[i].num){m=();cout<<num<<" is No."<<m/sizeof(staf1)<<endl;cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;find=true;break;}}if(!find)cout<<"can't find "<<num<<endl;cout<<"enter number you want search,enter 0 to stop.";cin>>num;}();return 0;}6:解法一#include <iostream>#include <strstream>using namespace std;struct student{int num;char name[20];double score;};int main(){student stud[3]={1001,"Li",78,1002,"Wang",,1004,"Fun",90},stud1[3];char c[50];int i;ostrstream strout(c,50);for(i=0;i<3;i++)strout<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<" ";strout<<ends;cout<<"array c:"<<endl<<c<<endl<<endl;istrstream strin(c,50);for(i=0;i<3;i++)strin>>stud1[i].num>>stud1[i].name>>stud1[i].score;cout<<"data from array c to array stud1:"<<endl;for(i=0;i<3;i++)cout<<stud1[i].num<<" "<<stud1[i].name<<" "<<stud1[i].score<<endl;cout<<endl;return 0;}6:解法二#include <iostream>#include <strstream>using namespace std;struct student{int num;char name[20];double score;};int main(){int i;student stud[3]={1001,"Li",78,1002,"Wang",,1004,"Fun",90},stud1[3]; char c[50];strstream strio(c,50,ios::in|ios::out);for(i=0;i<3;i++)strio<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<" ";strio<<ends;cout<<"array c:"<<endl<<c<<endl<<endl;for(i=0;i<3;i++)strio>>stud1[i].num>>stud1[i].name>>stud1[i].score;cout<<"data from array c to array stud1:"<<endl;for(i=0;i<3;i++)cout<<stud1[i].num<<" "<<stud1[i].name<<" "<<stud1[i].score<<endl; cout<<endl;return 0;}第八章1:#include <iostream>#include <cmath>using namespace std;double q(double,double,double);void main(){double a,b,c,p,x1,x2;cout<<"please enter a,b,c:";cin>>a>>b>>c;p=-b/(2*a);try{x1=p+q(a,b,c);x2=p-q(a,b,c);cout<<"x1="<<x1<<endl<<"x2="<<x2<<endl;}catch(double d){cout<<"a="<<a<<",b="<<b<<",c="<<c<<",disc="<<d<<",error!"<<endl;} cout<<"end"<<endl;}double q(double a,double b,double c){double disc;disc=b*b-4*a*c;if (disc<0) throw disc;return sqrt(disc)/(2*a);}2:#include <iostream>#include <string>using namespace std;class Student{public:Student(int n,string nam){cout<<"constructor-"<<n<<endl;num=n;name=nam;}~Student(){cout<<"destructor-"<<num<<endl;}void get_data();private:int num;string name;};void Student::get_data(){if(num==0) throw num;else cout<<num<<" "<<name<<endl;cout<<"in get_data()"<<endl;}void fun(){Student stud1(1101,"tan");();try{Student stud2(0,"Li");();}catch(int n){cout<<"num="<<n<<",error!"<<endl;}}int main(){cout<<"main begin"<<endl;cout<<"call fun()"<<endl;fun();cout<<"main end"<<endl;return 0;}3://main file#include <iostream>using namespace std;#include ""#include ""using namespace std;using namespace student1;int main(){Student stud1(1001,"Wang",18,"123 Beijing Road,Shanghua"); ();student2::Student stud2(1102,"Li",'f',;();return 0;}//,文件名为#include <string>namespace student1{class Student{public:Student(int n,string nam,int a,string addr){num=n;name=nam;age=a;address=addr;}void show_data();private:int num;string name;int age;string address;};void Student::show_data(){cout<<"num:"<<num<<" name:"<<name<<" age:"<<age<<" address:"<<address<<endl;}}//,文件名为#include <string>namespace student2{class Student{public:Student(int n,string nam,char s,float sco){num=n;name=nam;sex=s;score=sco;}void show_data();private:int num;string name;char sex;float score;};void Student::show_data(){cout<<"num:"<<num<<" name:"<<name<<" sex:"<<sex <<" score:"<<score<<endl; }}。

C++Primer(第4版)习题解答_十五章

C++Primer(第4版)习题解答_十五章

第十五章面向对象编程1。

什么是虚成员?在类中被声明为virtual的成员,基类希望这种成员在派生类中重定义。

除了构造函数外,任意非static成员都可以为虚成员。

2。

给出protected访问标号的定义。

它与private有何不同?protected为受保护的访问标号,protected成员可以被该类的成员、友元和派生类成员(非友元)访问,而不可以被该类型的普通用户访问。

而private成员,只能被基类的成员和友元访问,派生类不能访问。

3。

定义自己的Item_base类版本。

class Item_base{public:Item_base( const string &book = '', double sales_price = 0.0) :isbn( book ), price( sales_price ) { }string book( ) const{return isbn;}virtual double net_price( size_t n ) c onst{return price * n;}virtual ~Item_base() { }private:string isbn;protected:double price;};4。

图书馆可以借阅不同种类的资料—书、CD、DVD等等。

不同种类的借阅资料有不同的登记、检查和过期规则。

下面的类定义了这个应用程序可以使用的基类。

指出在所有借阅资料中,哪些函数可能定义为虚函数,如果有,哪些函数可能是公共的。

(注:假定LibMember 是表示图书馆读者的类,Date是表示特定年份的日历日期的类。

)class Library{bool check_out( const LibMember& );bool check_in( cosnt LibMember& );bool is_late( const Date& today );double apply_fine();ostream& print( ostream& = count );Date due_date() const;Date date_borrowed() const;string title() const;const LibMember& member() const;};因为有不同的登记、检查、和过期规则,所以bool check_out( const LibMember& );bool check_in( cosnt LibMember& );bool is_late( const Date& today );double apply_fine();ostream& print( ostream& = count );这几个函数应该被定义为虚函数,print函数可能用于打印不同的项目的内同,也定义为虚函数。

C++ primer plus 14章—15章课后答案

C++ primer plus 14章—15章课后答案

14.4#ifndef WORKERMI_H_#define WORKERMI_H_#include<iostream>#include<string>#include<cstdlib>usingnamespace std;class person{private:stringfirstname;stringlastname;protected:virtualvoid data(){cout<<"firstname: "<<firstname<<endl;cout<<"lastname: "<<lastname<<endl;};virtualvoid get(){getline(cin,firstname);cout<<"enter person's lastname: ";getline(cin,lastname);cin.get();}public:person():firstname("no one"),lastname("no one"){}person(string & s1,string & s2):firstname(s1),lastname(s2){} person(person & s){firstname=s.firstname;lastname=stname;}virtual ~person()=0;virtualvoid set()=0;virtualvoid show() =0;};class gunslinger:virtualpublic person{private:double time;int nick;protected:void data(){cout<<"time: "<<time<<endl;cout<<"nick: "<<nick<<endl;}void get(){cout<<"enter time to draw the gun: ";cin>>time;cout<<"enter nick of the gun: ";cin>>nick;cin.get();}public:gunslinger():person(),time(0),nick(0){}gunslinger(string & s1 ,string s2,double t=0,int n=0):person(s1,s2),time(t),nick(n){} gunslinger( person &p,double t=0,int n=0):person(p),time(t),nick(n){}void set(){cout<<"enter gunslinger's firstname: ";person::get();get();}void show(){cout<<"category: gunslinger\n";person::data();data();}double draw(){return time;}};class pokerplayer : virtualpublic person{private:int value;protected:void data(){cout<<"playing card: "<<value<<endl;}void get(){value=rand()%52;}public:pokerplayer():person(),value(0){}pokerplayer(string & s1,string & s2,int v=0):person(s1,s2),value(v){} pokerplayer(person &p,int v=0):person(p),value(v){}void set(){cout<<"enter pokerplayer'sfirstname: ";person::get();get();}void show(){cout<<"category: pokerplayer\n";person::data();data();}int draw(){return value;}};class baddude: public gunslinger, public pokerplayer{protected:void data(){gunslinger::data();pokerplayer::data();}void get(){gunslinger::get();pokerplayer::get();}public:baddude(){}baddude(string & s1,string & s2,double t=0,int n=0,int v=0):person(s1,s2),gunslinger(s1,s2,t,n),pokerplayer(s1,s2,v){}baddude(person &p,double t=0,int n=0,int v=0):person(p),gunslinger(p,t,n),pokerplayer(p,v){}baddude(person &p,double t=0,int n=0):person(p),gunslinger(p,t,n),pokerplayer(p){} baddude(person &p,int v=0):person(p),gunslinger(p),pokerplayer(p,v){}void set(){cout<<"enter baddue'sfirstname: ";person::get();get();}void show(){cout<<"category: baddue\n";person::data();data();}};#endif#include<iostream>#include<cstring>#include"person.h"int main(){usingnamespace std;person * lolas[5];int ct;for(ct=0;ct<5;ct++){char choice;cout<<"enter the category:\n"<<"g: gunslinger p: pokerplayer "<<"b: baddude q: quit\n";cin>>choice;while(strchr("gpbq",choice)==NULL){cout<<"please enter a g,p,b, or q: ";cin>>choice;}if (choice=='q')break;switch(choice){case'g': lolas[ct]=new gunslinger;break;case'p': lolas[ct]=new pokerplayer;break;case'b': lolas[ct]=new baddude;break;}cin.get();lolas[ct]->set();}cout<<"\nhere is your staff:\n";for(int i=0;i<5;i++){cout<<endl;lolas[i]->show();}for(int i=0;i<5;i++)delete lolas[i];cout<<"bye.\n";return 0;}14.5emp.h#include<iostream>#include<string>usingnamespace std;class abstr_emp{private:string fname;string lname;string job;public:abstr_emp(){fname="no";lname="no";job="no";}abstr_emp(const string &fn,const string &ln,const string & j):fname(fn),lname(ln),job(j){}virtualvoid showall() const{cout<<"firstname: "<<fname<<endl;cout<<"lastname: "<<lname<<endl;cout<<"job: "<<job<<endl;}virtualvoid setall(){cout<<"enter first name: ";cin>>fname;cin.get();cout<<"enter last name: ";cin>>lname;cin.get();cout<<"enter job: ";getline(cin,job);}friend std::ostream&operator<<(ostream&os,const abstr_emp& e){os<<"firstname: "<<e.fname<<endl;os<<"lastname: "<<e.lname<<endl;return os;};virtual ~abstr_emp()=0{};};class employee: public abstr_emp{public:employee():abstr_emp(){}employee(const string &fn,const string &ln,const string & j):abstr_emp(fn,ln,j){} virtualvoid showall () const{abstr_emp::showall();}virtualvoid setall(){abstr_emp::setall();}};class manager: virtualpublic abstr_emp{private:int inchargeof;protected:int inchargeof1() const {return inchargeof;}int& inchargeof1(){return inchargeof;}public:manager():abstr_emp(),inchargeof(0){}manager(const string &fn,const string &ln,const string&j,int ico=0):abstr_emp(fn,ln,j),inchargeof(ico){}manager(const abstr_emp&e,int ico):abstr_emp(e),inchargeof(ico){} manager(const manager & m):abstr_emp(m){inchargeof=m.inchargeof;}virtualvoid showall() const{abstr_emp::showall();cout<<"inchargeof: "<<inchargeof<<endl;}virtualvoid setall(){abstr_emp::setall();cout<<"enter inchargeof: ";cin>>inchargeof;while(cin.get()!='\n')continue;}};class fink:virtualpublic abstr_emp{private:string reportsto;protected:const string reportsto1() const{return reportsto;}string & reportsto1(){return reportsto;public:fink():abstr_emp(),reportsto("none"){}fink(const string &fn,const string &ln,const string &j,const string&rpo):abstr_emp(fn,ln,j),reportsto(rpo){}fink(const abstr_emp&e,const string &rpo):abstr_emp(e),reportsto(rpo){}fink(const fink & e):abstr_emp(e){reportsto=e.reportsto;}virtualvoid showall() const{abstr_emp::showall();cout<<"reportsto: "<<reportsto<<endl;}virtualvoid setall(){abstr_emp::setall();cout<<"enter reportsto: ";cin>>reportsto;while(cin.get()!='\n')continue;}};class highfink:public manager,public fink{public:highfink(){}highfink(const string &fn,const string &ln,const string &j,const string&rpo,int ico):abstr_emp(fn,ln,j),fink(fn,ln,j,rpo),manager(fn,ln,j,ico){} highfink(const abstr_emp&e,const string&rpo,int ico):abstr_emp(e),manager(e,ico),fink(e,rpo){}highfink(const fink &f,int ico):abstr_emp(f),manager(f,ico){}highfink(const manager &m,const string &rpo):abstr_emp(m),manager(m),fink(m,rpo){} highfink(const highfink& h):abstr_emp(h),manager(h),fink(h){}virtualvoid showall() const{abstr_emp::showall();cout<<"inchargeof: "<<manager::inchargeof1()<<endl;cout<<" reportsto: "<<fink::reportsto1()<<endl;virtualvoid setall(){abstr_emp::setall();cout<<"enter inchargeof: ";cin>>manager::inchargeof1();while(cin.get()!='\n')continue;cout<<"enter reportsto: ";cin>>fink::reportsto1();while(cin.get()!='\n')continue;}};main.cpp#include<iostream>#include"emp.h"usingnamespace std;int main(){employee em("Trip","Harris","Thumper");cout<<em<<endl;em.showall();manager ma("Amorphia","Spindragon","Nuancer",5);cout<<ma<<endl;ma.showall();fink fi("Matt","Oggs","Oiler","Juno Barr");cout<<fi<<endl;fi.showall();highfinkhf(ma,"Curly Kew");hf.showall();cout<<"Press a key for next phase:\n";cin.get();highfink hf2;hf2.setall();cout<<"Using an abstr_emp * pointer: \n";abstr_emp * tri[4]={&em, &fi, &hf, &hf2};for(int i=0;i<4;i++)tri[i]->showall();cin.get();return 0;}15.1remote.h#include<iostream>usingnamespace std;class tv{friendclass remote;public:enum{off,on};enum{minval,maxval=20};enum{antenna,cable};enum{Tv,dvd};tv(int s=off,intmc=125):state(s),volume(5),maxchannel(mc),channel(2),mode(cable),input(Tv){} void onoff(){state=(state==on)?off:on;}bool ison()const{return state==on;}bool volup(){if(volume<maxval){volume++;returntrue;}elsereturnfalse;}bool voldown(){if(volume>minval){volume--;returntrue;}elsereturnfalse;}void chanup(){if(channel<maxchannel)channel++;elsechannel=1;}void chandown(){if(channel>1)channel--;elsechannel=20;}void set_mode(){mode=(mode==antenna)?cable:antenna;}void set_input(){input=(input=Tv)?dvd: Tv;}void settings()const{cout<<"tv is "<<(state==off?"off":"on")<<endl;if(state==on){cout<<"volume setting = "<<volume<<endl;cout<<"channel setting = "<<channel<<endl;cout<<"mode = "<<(mode == antenna?"antenna":"cable")<<endl;cout<<"input = "<<(input == Tv?"Tv":"dvd")<<endl;}}void set_condition(remote & r);private:int state;int volume;int maxchannel;int channel;int mode;int input;};class remote{friendclass tv;enum{default1,interact};private:int mode;int condition;public:remote(int m=tv::Tv,int c=default1):mode(m),condition(c){}bool volup(tv& t){return t.volup();}bool voldown(tv& t){return t.voldown();}void onoff(tv& t){t.onoff();}void chanup(tv& t){t.chanup();}void chandown(tv& t){t.chandown();}void set_chan(tv&t,int c){t.channel=c;}void set_mode(tv& t){t.set_mode();}void set_input(tv& t){t.set_input();}void show(){cout<<"remote condition: "<<condition<<endl;}void set_condition(){condition=(condition==default1)?interact:default1;} };inlinevoid tv:: set_condition(remote & r){if(tv::state==on)r.set_condition();}main.cpp#include<iostream>#include"remote.h"int main(){usingnamespace std;tv s42;cout<<"initial settings for 42\"Tv: \n";s42.settings();s42.onoff();s42.chanup();cout<<"\nadjusted settings for 42\"Tv: \n";s42.settings();remote grey;grey.set_chan(s42,10);grey.volup(s42);grey.volup(s42);cout<<"\n42\"settings after using remote: \n";s42.settings();grey.show();s42.set_condition(grey);cout<<"set condition using tv: "<<endl;grey.show();tv s58(tv::on);s58.set_mode();grey.set_chan(s58,28);cout<<"\n58\"settings: \n";s58.settings();cin.get();return 0;}15.2error.h#include<exception>#include<iostream>usingnamespace std;class bad_hmean:public exception{public:bad_hmean(){}constchar * what(){ return"bad arguments to hmean()";} };class bad_gmean:public exception{public:bad_gmean(){}constchar * what(){return"bad arguments to gmean()";} };main.cpp#include<iostream>#include"erroe.h"#include<cmath>double hmean(double a,double b);double gmean(double a,double b);int main(){usingnamespace std;double x,y,z;cout<<"enter two numbers: ";while(cin>>x>>y){try{z=hmean(x,y);cout<<"harmonic mean of "<<x<<" and "<<y<<" is "<<z<<endl;cout<<"geometric mean of "<<x<<" and "<<y<<" is "<<gmean(x,y)<<endl;cout<<"enter next set of numbers <q to quit>: ";}catch (bad_hmean&bg){cout<<bg.what()<<endl;cout<<"try again.\n";continue;}catch (bad_gmean& hg){cout<<hg.what()<<endl;cout<<"values used: "<<x<<", "<<y<<endl;cout<<"sorry,you don't get to play any more.\n";break;}}cout<<"bye!\n";cin.get();cin.get();return 0;}double hmean(double a,double b){if (a==-b)throw bad_hmean();return 2.0*a*b/(a+b);}double gmean(double a,double b){if(a<0||b<0)throw bad_gmean();return std::sqrt(a*b);}15.3erroe.h#include<exception>#include<iostream>usingnamespace std;class logic:public exception{private:double v1;double v2;public:logic(double a=0,double b=0):v1(a),v2(b){}virtualvoid show() const{cout<<"values used: "<<v1<<","<<v2<<endl;}};class bad_hmean:public logic{public:bad_hmean(double a=0,double b=0):logic(a,b){} void show() const{logic::show();cout<<"invalid argument: a= -b\n";}};class bad_gmean:public logic{public:bad_gmean(double a=0,double b=0):logic(a,b){}void show()const{logic::show();cout<<"gmean() arguments: "<<" should be >=0\n";}};main.cpp#include<iostream>#include"erroe.h"#include<cmath>double hmean(double a,double b);double gmean(double a,double b);int main(){usingnamespace std;double x,y,z;cout<<"enter two numbers: ";while(cin>>x>>y){try{z=hmean(x,y);cout<<"harmonic mean of "<<x<<" and "<<y<<" is "<<z<<endl;cout<<"geometric mean of "<<x<<" and "<<y<<" is "<<gmean(x,y)<<endl;cout<<"enter next set of numbers <q to quit>: ";}catch(logic & e){e.show();break;}/*catch (bad_hmean&bg){cout<<bg.what()<<endl;bg.mesg();cout<<"try again.\n";continue;}catch (bad_gmean& hg){cout<<hg.what();hg.mesg();cout<<"values used: "<<x<<", "<<y<<endl;cout<<"sorry,you don't get to play any more.\n";break;}*/}cout<<"bye!\n";cin.get();cin.get();return 0;}double hmean(double a,double b){if (a==-b)throw bad_hmean(a,b);return 2.0*a*b/(a+b);}double gmean(double a,double b){if(a<0||b<0)throw bad_gmean(a,b);return std::sqrt(a*b);}15.4sales.h#include<stdexcept>#include<string>usingnamespace std;class sales{public:enum {MONTHS=12};class bad_index:public logic_error{private:int bi;public:explicit bad_index(int ix,const string & s="index error in sales object\n");int bi_val() const{return bi;}virtual ~bad_index() throw() {}};explicit sales(int yy=0);sales(int yy,constdouble * gr, int n);virtual ~sales(){}int year1() const {return year;}virtualdoubleoperator[](int i)const;virtualdouble&operator[](int i);private:double gross[MONTHS];int year;};class labeledsales: public sales{private:string label;public:class nbad_index: public sales::bad_index{private:stringlbl;public:nbad_index(const string &lb,int ix,const string & s="Index error in labeledsales object\n");const string &label_val()const{return lbl;}virtual ~nbad_index() throw(){}};explicit labeledsales(const string &lb="none",int yy=0);labeledsales(const string &lb,int yy, constdouble * gr ,int n);virtual ~labeledsales(){}const string & label1() const {return label;}virtualdoubleoperator[](int i)const;virtualdouble&operator[](int i);};sales.cpp#include"sale.h"usingnamespace std;sales::bad_index::bad_index(int ix,const string & s):logic_error(s),bi(ix) {}sales::sales(int yy){year=yy;for(int i=0;i<MONTHS;++i)gross[i]=0;}sales::sales(int yy,constdouble * gr,int n){year=yy;int lim=(n<MONTHS)?n:MONTHS;int i;for(i=0;i<lim;++i)gross[i]=gr[i];for(;i<MONTHS;++i)gross[i]=0;}double sales::operator[](int i)const{if(i<0||i>=MONTHS)thrownew bad_index(i);return gross[i];}double& sales::operator[](int i){if(i<0||i>=MONTHS)thrownew bad_index(i);return gross[i];}labeledsales::nbad_index::nbad_index(const string &lb,int ix,const string & s):sales::bad_index(ix,s){lbl=lb;}labeledsales::labeledsales(const string &lb, int yy):sales(yy){label=lb;}labeledsales::labeledsales(const string &lb,int yy,constdouble * gr,int n):sales(yy,gr,n) {label=lb;}double labeledsales::operator[](int i)const{if(i<0||i>=MONTHS)thrownew nbad_index(label1(),i);return sales::operator[](i);}double&labeledsales::operator[](int i){if(i<0||i>=MONTHS)thrownew nbad_index(label1(),i);return sales::operator[](i);}main.cpp#include<iostream>#include"sale.h"int main(){usingnamespace std;double vals1[12]={1220,1100,1122,2212,1232,2334,2884,2393,3302,2922,3002,3544};double vals2[12]={12,11,22,21,32,34,28,29,33,29,32,35};sales sales1(2011,vals1,12);labeledsales sales2("blogstar",2012,vals2,12);cout<<"first try block:\n";labeledsales::nbad_index * ps;try{int i;cout<<"year = "<<sales1.year1()<<endl;for(i=0;i<12;++i){cout<<sales1[i]<<" ";if(i % 6==5)cout<<endl;}cout<<"year = "<<sales2.year1()<<endl;cout<<"label = "<<bel1()<<endl;for(i=0;i<=12;++i){cout<<sales2[i]<<" ";if(i % 6==5)cout<<endl;}cout<<"end of try block 1.\n";}catch(sales::bad_index * bad){cout<<bad->what();cout<<"bad index: "<<bad->bi_val()<<endl;if(ps=dynamic_cast<labeledsales::nbad_index * >(bad)) cout<<"company: "<<ps->label_val()<<endl;}labeledsales::nbad_index * ps1;try{sales2[2]=37.5;sales1[20]=23345;cout<<"end of try block 2.\n";}catch(sales::bad_index * bad){cout<<bad->what();cout<<"bad index: "<<bad->bi_val()<<endl;if(ps1=dynamic_cast<labeledsales::nbad_index * >(bad)) cout<<"company: "<<ps1->label_val()<<endl;}cout<<"done\n";cin.get();cin.get();return 0;}。

c面向对象程序设计课后习题答案

c面向对象程序设计课后习题答案

c面向对象程序设计课后习题答案C面向对象程序设计课后习题答案在学习C面向对象程序设计课程的过程中,课后习题是巩固知识、提升能力的重要途径。

通过认真完成习题,我们可以更好地理解课程内容,掌握编程技巧,提高解决问题的能力。

下面我们将针对一些常见的C面向对象程序设计课后习题进行答案解析。

1. 请编写一个C++程序,实现一个简单的学生信息管理系统,包括学生姓名、学号、成绩等信息的录入、查询和修改功能。

答案解析:首先,我们需要定义一个学生类,包括姓名、学号、成绩等属性,并实现相应的方法来实现信息的录入、查询和修改功能。

然后在主函数中创建学生对象,调用相应的方法即可实现学生信息管理系统。

2. 编写一个C++程序,实现一个简单的图书管理系统,包括图书名称、作者、出版社等信息的录入、查询和删除功能。

答案解析:同样地,我们需要定义一个图书类,包括图书名称、作者、出版社等属性,并实现相应的方法来实现信息的录入、查询和删除功能。

在主函数中创建图书对象,调用相应的方法即可实现图书管理系统。

3. 设计一个C++程序,模拟实现一个简单的银行账户管理系统,包括账户余额、存款、取款等功能。

答案解析:在这个问题中,我们需要定义一个银行账户类,包括账户余额、存款、取款等属性,并实现相应的方法来实现账户管理系统。

在主函数中创建账户对象,调用相应的方法即可实现银行账户管理系统。

通过以上习题的解答,我们可以看到C面向对象程序设计的重要性和实际应用。

通过不断地练习和实践,我们可以更好地掌握面向对象程序设计的知识和技能,提高编程能力,为今后的工作和学习打下坚实的基础。

希望同学们能够认真对待课后习题,不断提升自己的编程水平。

面向对象课后题答案

面向对象课后题答案
C. 使用内联函数,可以加快程序执行的速度,但会增加程序代码的大小
D. 使用内联函数,可以减小程序代码大小,但使程序执行的速度减慢
【结果分析】
内联函数主要是解决程序的运行效率问题。在程序编译时,编译系统将程序中出现内联函数调用的地方用函数体进行替换,进而减少了程序运行的时间,但会增加程序代码的大小。它是以空间换取时间,因此内联函数适用于功能不太复杂,但要求被频繁调用的函数。
B. 对象实际是功能相对独立的一段程序
C. 各个对象间的数据可以共享是对象的一大优点
D. 在面向对象的程序中,对象之间只能通过消息相互通信
【结果分析】
对象是计算机内存中的一块区域。在对象中,不但存有数据,而且存有代码,使得每个对象在功能上相互之间保持相对独立。对象之间存在各种联系,但它们之间只能通过消息进行通信。
C. C++对C语言进行了一些改进 D. C++和C语言都是面向对象的
【结果分析】
C语言是面向过程的。C++语言是一种经过改进的更为优化的C语言,是一种混合型语言,既面向过程也面向对象。
(6) 面向对象的程序设计将数据结构与( A )放在一起,作为一个相互依存、不可分割的整体来处理。
A. 算法 B. 信息 C. 数据隐藏 D. 数据抽象
四、 判断题
(1) 在高级程序设计语言中,一般用类来实现对象,类是具有相同属性和行为的一组对象的集合,它是创建对象的模板。( √ )
(2) C++语言只支持面向对象技术的抽象性、封装性、继承性等特性,而不支持多态性。( × )
【结果分析】
C++语言不仅支持面向对象技术的抽象性、封装性、继承性等特性,而且支持多态性。

【C++PrimerPlus】编程练习答案——第15章

【C++PrimerPlus】编程练习答案——第15章

【C++PrimerPlus】编程练习答案——第15章 1// chapter15_1_tvremote.h23 #ifndef LEARN_CPP_CHAPTER15_1_TVREMOTE_H4#define LEARN_CPP_CHAPTER15_1_TVREMOTE_H5class Remote;6class Tv {7private:8int state;9int volume;10int maxchannel;11int channel;12int mode;13int input;14public:15 friend class Remote;16enum {OFF, ON};17enum {MinVal, MaxVal = 20};18enum {Antenna, Cable};19enum {TV, DVD};2021 Tv(int s = OFF, int mc = 125) : state(s), volume(5), maxchannel(mc), channel(2), mode(Cable), input(TV) {}22void onoff() {state = (state == ON)? OFF : ON;}23bool ison() const {return state == ON;}24bool volup();25bool voldown();26void chanup();27void chandown();28void set_mode() {mode = (mode == Antenna)? Cable : Antenna;}29void set_input() {input = (input == TV)? DVD : TV;}30void settings() const;31void set_status(Remote & r);32 };3334class Remote {35private:36int mode;37int status; // 常规还是互动模式38public:39 friend class Tv;40enum {Normal, Interacte};4142 Remote(int m = Tv::TV) : mode(m), status(Normal){}43bool volup(Tv & t) {return t.volup();}44bool voldown(Tv & t) {return t.voldown();}45void onoff(Tv & t) {t.onoff();}46void chanup(Tv & t) {t.chanup();}47void chandown(Tv & t) {t.chandown();}48void set_chan(Tv & t, int c) {t.channel = c;}49void set_input(Tv & t) {t.set_input();}50void showstatus() const;51 };525354#endif//LEARN_CPP_CHAPTER15_1_TVREMOTE_H555657// chapter15_1_tvremote.cpp5859 #include "chapter15_1_tvremote.h"60 #include <iostream>6162bool Tv::volup() {63if (volume < MaxVal) {64 ++ volume;65return true;66 }67return false;68 }6970bool Tv::voldown() {71if (volume > MinVal) {72 -- volume;73return true;74 }75return false;76 }7778void Tv::chanup() {79if (channel < maxchannel)80 ++ channel;81else82 channel = 1;83 }8485void Tv::chandown() {86if (channel > 1)87 -- channel;88else89 channel = maxchannel;90 }9192void Tv::settings() const {93using namespace std;94 cout << "TV is " << (state == OFF? "OFF" : "ON") << endl;95if (state == ON) {96 cout << "volume setting = " << volume << endl;97 cout << "channel setting = " << channel << endl;98 cout << "mode = " << (mode == Antenna? "antenna" : "cable") << endl;99 cout << "input = " << (input == TV? "TV" : "DVD") << endl;100 }101 }102103void Tv::set_status(Remote &r) {104if (state == ON)105 r.status = r.status == Remote::Interacte? Remote::Normal : Remote::Interacte; 106 }107108void Remote::showstatus() const {109using namespace std;110 cout << "status = " << (status == Interacte? "Interacte" : "Normal") << endl;111 }112113// run114115void ch15_1() {116using namespace std;117 Tv s42;118 cout << "Initial settings for 42\" TV:\n";119 s42.settings();120 s42.onoff();121 s42.chanup();122 s42.chanup();123 cout << "\nAdjusted settings for 42\" TV:\n";124 s42.settings();125126 Remote grey;127 grey.set_chan(s42, 10);128 grey.volup(s42);129 grey.volup(s42);130 cout << "\n42\" settings after using remote:\n";131 s42.settings();132133 Tv s58(Tv::ON);134 s58.set_mode();135 grey.set_chan(s58, 28);136 cout << "\n58\" settings:\n";137 s58.settings();138139 cout << "\n58\" status:\n";140 grey.showstatus();141 s58.set_status(grey);142 grey.showstatus();143 }1// chapter15_2_stdexcept.h23 #ifndef LEARN_CPP_CHAPTER15_2_STDEXCEPT_H4#define LEARN_CPP_CHAPTER15_2_STDEXCEPT_H56 #include <stdexcept>7 #include <cmath>89class meanlogicerr : public std::logic_error {10public:11 meanlogicerr() : logic_error("") {}12const char * what() {return"bad arguments to hmean() or gmean()";}13 };1415#endif//LEARN_CPP_CHAPTER15_2_STDEXCEPT_H1617// run1819double hmean(double a, double b) {20if (a == b)21throw meanlogicerr();22return2.0 * a * b / (a + b);23 }2425double gmean(double a, double b) {26if (a < 0 || b < 0)27throw meanlogicerr();28return std::sqrt(a * b);29 }3031void ch15_2() {32using namespace std;33try {cout << "x = 1, y = 1, hmean = " << hmean(1, 1) << endl;}34catch (meanlogicerr & me) {cout << me.what() << endl;}35try {cout << "x = -1, y = 1, gmean = " << gmean(-1, 1) << endl;}36catch (meanlogicerr & me) {cout << me.what() << endl;}37try {cout << "x = 1, y = 2, hmean = " << hmean(1, 2) << endl;}38catch (meanlogicerr & me) {cout << me.what() << endl;}39try {cout << "x = 1, y = 1, gmean = " << gmean(1, 1) << endl;}40catch (meanlogicerr & me) {cout << me.what() << endl;}41 }1// chapter15_3_meanerr.h23 #ifndef LEARN_CPP_CHAPTER15_3_MEANERR_H4#define LEARN_CPP_CHAPTER15_3_MEANERR_H56 #include <stdexcept>7 #include <iostream>8 #include <string>910class twodouargserr : public std::logic_error {11private:12double arg1;13double arg2;14 std::string funcname;15public:16 twodouargserr(double a1 = 0, double a2 = 0, const char * f = "none")17 : arg1(a1), arg2(a2), funcname(f), std::logic_error("") {}18virtual const char * what() {return"invalid args";}19virtual void msg(){std::cout << funcname << "() logicerr, arg1: " << arg1 << " arg2: " << arg2 << std::endl;} 20 };2122class hmean_err : public twodouargserr {23public:24 hmean_err(double a1 = 0, double a2 = 0, const char * f = "none")25 : twodouargserr(a1, a2, f) {}26virtual const char * what() {return"invalid args";}27virtual void msg(){twodouargserr::msg();}28 };2930class gmean_err : public twodouargserr {31public:32 gmean_err(double a1 = 0, double a2 = 0, const char * f = "none")33 : twodouargserr(a1, a2, f) {}34virtual const char * what() {return"invalid args";}35virtual void msg(){twodouargserr::msg();}36 };373839#endif//LEARN_CPP_CHAPTER15_3_MEANERR_H4041// run4243double hmean2(double a, double b) {44if (a == b)45throw hmean_err(a, b, __func__ );46return2.0 * a * b / (a + b);47 }4849double gmean2(double a, double b) {50if (a < 0 || b < 0)51throw gmean_err(a, b, __func__ );52return std::sqrt(a * b);53 }54void ch15_3() {55using namespace std;56try {cout << "x = 1, y = 1, hmean = " << hmean2(1, 1) << endl;}57catch (hmean_err & he) {cout << he.what() << endl; he.msg();}58try {cout << "x = 1, y = 2, hmean = " << hmean2(1, 2) << endl;}59catch (hmean_err & he) {cout << he.what() << endl; he.msg();}60try {cout << "x = -1, y = 1, gmean = " << gmean2(-1, 1) << endl;}61catch (gmean_err & ge) {cout << ge.what() << endl; ge.msg();}62try {cout << "x = 1, y = 1, hmean = " << gmean2(1, 1) << endl;}63catch (gmean_err & ge) {cout << ge.what() << endl; ge.msg();}64 }剩下的有空写。

C++Primer第5版第十五章课后练习答案

C++Primer第5版第十五章课后练习答案

C++Primer第5版第⼗五章课后练习答案练习15.1成员函数应在其声明之前动态绑定。

基类中的虚成员希望其派⽣类定义其⾃⼰的版本。

特别是基类通常应定义虚析构函数,即使它不起作⽤。

练习15.2派⽣类能访问基类的共有成员⽽不能访问私有成员,但派⽣类能访问基类的protected访问运算符描述的成员,⽽禁⽌其它⽤户访问练习15.3#include <string>#include <iostream>#ifndef _QUOTE_H_#define _QUOTE_H_class Quote{public:Quote()=default;Quote(const std::string& book, double sales_price) :bookNo(book), price(sales_price) {}std::string isbn() const { return bookNo; }virtual double net_price(std::size_t n)const { return n * price; }virtual ~Quote() = default;private:std::string bookNo;protected:double price = 0.0;};double print_total(std::ostream& os, const Quote& item, size_t n){double ret = _price(n);os << "ISBN: " << item.isbn() << " # sold: " << n << " total due: " << ret << std::endl;return ret;}#endif// !_QUOTE_H_练习15.4class Base { ... };(a) class Derived : public Derived { ... }; // 错误,类重复定义,不能⾃⼰继承⾃⼰(b) class Derived : private Base { ... }; // 正确(c) class Derived : public Base; // 错误,类的声明包含类名但不包含类派⽣列表练习15.5class Bulk_quote:public Quote{public:Bulk_quote() = default;Bulk_quote(const std::string&, double, std::size_t,double);double net_price(std::size_t)const override;protected:std::size_t min_qty = 0;double discount = 0.0;};Bulk_quote::Bulk_quote(const std::string& book, double p, std::size_t qty,double disc) :Quote(book, p), min_qty(qty), discount(disc) {}inline double Bulk_quote::net_price(std::size_t cnt) const{if (cnt >= min_qty)return cnt * (1 - discount) * price;elsereturn cnt * price;}练习15.6int main(int argc, char* argv[]){Bulk_quote bq;Quote q(bq);print_total(cout, q, 1);print_total(cout, bq, 1);return0;}练习15.7class Limit_quote : public Bulk_quote{public:Limit_quote() = default;Limit_quote(const std::string&, double, std::size_t, std::size_t, double);double net_price(std::size_t)const override;private:std::size_t max_qty = 0;};Limit_quote::Limit_quote(const std::string& book, double p, std::size_t min, std::size_t max,double disc) :Bulk_quote(book, p,min,disc), max_qty(max){}inline double Limit_quote::net_price(std::size_t cnt) const{if(cnt>=max_qty)return max_qty * (1 - discount) * price+(cnt- max_qty)*price;else if (cnt >= min_qty)return cnt * (1 - discount) * price;elsereturn cnt * price;}练习15.8静态类型:在编译时总是已知的,它是变量声明时的类型或表达式⽣成的类型动态类型:变量或表达式表⽰的内存中的对象的类型。

《CPrimer》第15章学习笔记

《CPrimer》第15章学习笔记

《CPrimer》第15章学习笔记第15章:面向对象编程——面向对象编程基于三个基本概念:数据抽象,继承,动态绑定。

——用类进行数据抽象——用类派生从一个类继承另一个类:派生类继承基类成员;——动态绑定使编译器能够在运行时决定是使用基类中定义的函数还是派生类中定义的函数。

——能够容易地定义与其他类相似但又不相同的新类,能够更容易地编写忽略这些相似类型之间区别的程序。

——面向对象编程的关键思想是多态性(polymorphim)——继承而相关联的类型为多态类型。

——派生类(derivedcla)能够继承基类(baecla)定义的成员——派生类可以无须改变而使用那些与派生类型具体特性不相关的操作——派生类可以重定义那些与派生类型相关的成员函数,将函数特化,考虑派生类型的特性。

——在C++中,基类必须指出希望派生类重定义哪些函数,定义为virtual的函数是基类期待派生类重新定义的,基类希望派生类继承的函数不能定义为虚函数。

——我们能够编写程序使用继承层次中任意类型的对象,无须关心对象的具体类型。

——可以认为protected访问标号是private和public的混合:——1.像private成员一样,protected成员不能被类的用户访问。

——2.像public成员一样,protected成员可被该类的派生类访问。

——派生类只能通过派生类对象访问其基类的protected成员,派生类对其基类类型对象的protected成员没有特殊访问权限。

——简单地说:提供给派生类型接口是protected成员和public成员的集合。

——为了定义派生类,使用类派生列表(claderivationlit)指定基类。

——claclaname:acce-labelbae-cla——这里的acce-label是public、protected或private,bae-cla是已定义的类的名字。

——一旦函数在基类中声明为虚函数,它就一直为虚函数,派生类无法改变该函数为虚函数这一事实。

答案-c++面向对象程序设计课后习题答案(谭浩强版)

答案-c++面向对象程序设计课后习题答案(谭浩强版)

第一章5:#include <iostream> using namespace std;int main(){cout<<"This"<<"is"; cout<<"a"<<"C++";cout<<"program."<<endl; return 0;}6:#include <iostream> using namespace std;int main(){int a,b,c;a=10;b=23;c=a+b;cout<<"a+b=";cout<<c;cout<<endl;return 0;}7:#include <iostream> using namespace std;int main(){int a,b,c;int f(int x,int y,int z); cin>>a>>b>>c;c=f(a,b,c);cout<<c<<endl;return 0;}int f(int x,int y,int z){int m;else m=y;if (z<m) m=z;return(m);}8: #include <iostream> using namespace std;int main(){int a,b,c;cin>>a>>b;c=a+b;cout<<"a+b="<<a+b<<endl; return 0;}9:#include <iostream>using namespace std;int main(){int add(int x,int y);int a,b,c;cin>>a>>b;c=add(a,b);cout<<"a+b="<<c<<endl; return 0;}int add(int x,int y){int c;c=x+y;return(c);}10:#include <iostream>using namespace std;int main(){void sort(int x,int y,int z); int x,y,z;cin>>x>>y>>z;return 0;}void sort(int x, int y, int z){int temp;if (x>y) {temp=x;x=y;y=temp;} //{ }内3个语句的作用是将x和y的值互换) if (z<x) cout<<z<<','<<x<<','<<y<<endl;else if (z<y) cout<<x<<','<<z<<','<<y<<endl;else cout<<x<<','<<y<<','<<z<<endl;}11:#include <iostream>using namespace std;int main(){int max(int a,int b,int c=0);int a,b,c;cin>>a>>b>>c;cout<<"max(a,b,c)="<<max(a,b,c)<<endl;cout<<"max(a,b)="<<max(a,b)<<endl;return 0;}int max(int a,int b,int c){if(b>a) a=b;if(c>a) a=c;return a;}12:#include <iostream>using namespace std;int main(){void change(int ,int );int a,b;cin>>a>>b;if(a<b) change(a,b);cout<<"max="<<a<<" min="<<b<<endl;return 0;}void change(int ,int ){int r1,r2,temp;temp=r1;r1=r2;r2=temp;}13:#include <iostream>using namespace std;int main(){void sort(int &,int &,int &);int a,b,c,a1,b1,c1;cout<<"Please enter 3 integers:";cin>>a>>b>>c;a1=a;b1=b;c1=c;sort(a1,b1,c1);cout<<a<<" "<<b<<" "<<c<<" in sorted order is "; cout<<a1<<" "<<b1<<" "<<c1<<endl;return 0;}void sort(int &i,int &j,int &k){ void change(int &,int &);if (i>j) change(i,j);if (i>k) change(i,k);if (j>k) change(j,k);}void change(int &x,int &y){ int temp;temp=x;x=y;y=temp;}14:#include <iostream>#include <string>using namespace std;int main(){ string s1="week",s2="end";cout<<"s1="<<s1<<endl;cout<<"s2="<<s2<<endl;s1=s1+s2;cout<<"The new string is:"<<s1<<endl;return 0;}15:#include <iostream>#include <string>using namespace std;int main(){ string str;int i,n;char temp;cout<<"please input a string:";cin>>str;n=str.size();for(i=0;i<n/2;i++){temp=str[i];str[i]=str[n-i-1];str[n-i-1]=temp;}cout<<str<<endl;return 0;}16:#include <iostream>#include <string>using namespace std;int main(){ int i;string str[5]={"BASIC","C","FORTRAN","C++","PASCAL"}; void sort(string []);sort(str);cout<<"the sorted strings :"<<endl;for(i=0;i<5;i++)cout<<str[i]<<" ";cout<<endl;return 0;}void sort(string s[]){int i,j;string t;for (j=0;j<5;j++)for(i=0;i<5-j;i++)if (s[i]>s[i+1]){t=s[i];s[i]=s[i+1];s[i+1]=t;}}17: #include <iostream>#include <string>using namespace std;int main(){long c[5]={10100,-123567, 1198783,-165654, 3456}; int a[5]={1,9,0,23,-45};float b[5]={2.4, 7.6, 5.5, 6.6, -2.3 };void sort(int []);void sort(float []);void sort(long []);sort(a);sort(b);sort(c);return 0;}void sort(int a[]){int i,j,t;for (j=0;j<5;j++)for(i=0;i<5-j;i++)if (a[i]>a[i+1]){t=a[i];a[i]=a[i+1];a[i+1]=t;}cout<<"the sorted numbers :"<<endl;for(i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl<<endl;}void sort(long a[]){int i,j;long t;for (j=0;j<5;j++)for(i=0;i<5-j;i++)if (a[i]>a[i+1]){t=a[i];a[i]=a[i+1];a[i+1]=t;}cout<<"the sorted numbers :"<<endl;for(i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl<<endl;}void sort(float a[]){int i,j;float t;for (j=0;j<5;j++)for(i=0;i<5-j;i++)if (a[i]>a[i+1]){t=a[i];a[i]=a[i+1];a[i+1]=t;}cout<<"the sorted numbers :"<<endl;for(i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl<<endl;}18: #include <iostream>#include <string>using namespace std;template <typename T>void sort(T a[]){int i,j,min;T t;for(i=0;i<5;i++){min=i;for (j=i+1;j<5;j++)if(a[min]>a[j]) min=j;t=a[i]; a[i]=a[min]; a[min]=t;}cout<<"the sorted numbers :"<<endl;for(i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl<<endl;}int main(){ int a[5]={1,9,0,23,-45};float b[5]={2.4, 7.6, 5.5, 6.6, -2.3 };long c[5]={10100,-123567, 1198783,-165654, 3456}; sort(a);sort(b);sort(c);return 0;}第二章1#include <iostream>using namespace std;class Time{public:void set_time();void show_time();private: //成员改为公用的int hour;int minute;int sec;};void Time::set_time() //在main函数之前定义{cin>>hour;cin>>minute;cin>>sec;}void Time::show_time() //在main函数之前定义{cout<<hour<<":"<<minute<<":"<<sec<<endl;}int main(){Time t1;t1.set_time();t1.show_time();return 0;}2:#include <iostream>using namespace std;class Time{public:void set_time(void){cin>>hour;cin>>minute;cin>>sec;void show_time(void){cout<<hour<<":"<<minute<<":"<<sec<<endl;}private: int hour;int minute;int sec;};Time t;int main(){t.set_time();t.show_time();return 0;}3:#include <iostream>using namespace std;class Time{public:void set_time(void);void show_time(void);private:int hour;int minute;int sec;};void Time::set_time(void){cin>>hour;cin>>minute;cin>>sec;}void Time::show_time(void){cout<<hour<<":"<<minute<<":"<<sec<<endl;}Time t;int main(){ t.set_time();t.show_time();return 0;}//xt2-4-1.cpp(main.cpp)#include <iostream>using namespace std;#include "xt2-4.h"int main(){Student stud;stud.set_value();stud.display();return 0;}//xt2-4-2.cpp(即student.cpp)#include "xt2-4.h" //在此文件中进行函数的定义#include <iostream>using namespace std; //不要漏写此行void Student::display( ){ cout<<"num:"<<num<<endl;cout<<"name:"<<name<<endl;cout<<"sex:"<<sex<<endl;}void Student::set_value(){ cin>>num;cin>>name;cin>>sex;}5://xt2-5-1.cpp(file1.cpp)#include <iostream>#include "xt2-5.h"int main(){Array_max arrmax;arrmax.set_value();arrmax.max_value();arrmax.show_value();return 0;}//xt2-5-2.cpp(arraymax.cpp)#include <iostream>using namespace std;#include "xt2-5.h"void Array_max::set_value()for (i=0;i<10;i++)cin>>array[i];}void Array_max::max_value(){int i;max=array[0];for (i=1;i<10;i++)if(array[i]>max) max=array[i];}void Array_max::show_value(){cout<<"max="<<max<<endl;}6:解法一#include <iostream>using namespace std;class Box{public:void get_value();float volume();void display();public:float lengh;float width;float height;};void Box::get_value(){ cout<<"please input lengh, width,height:"; cin>>lengh;cin>>width;cin>>height;}float Box::volume(){ return(lengh*width*height);}void Box::display(){ cout<<volume()<<endl;}{Box box1,box2,box3;box1.get_value();cout<<"volmue of bax1 is ";box1.display();box2.get_value();cout<<"volmue of bax2 is ";box2.display();box3.get_value();cout<<"volmue of bax3 is ";box3.display();return 0;}解法二:#include <iostream>using namespace std;class Box{public:void get_value();void volume();void display();public:float lengh;float width;float height;float vol;};void Box::get_value(){ cout<<"please input lengh, width,height:"; cin>>lengh;cin>>width;cin>>height;}void Box::volume(){ vol=lengh*width*height;}void Box::display(){ cout<<vol<<endl;}int main(){Box box1,box2,box3;box1.get_value();box1.volume();cout<<"volmue of bax1 is ";box1.display();box2.get_value();box2.volume();cout<<"volmue of bax2 is ";box2.display();box3.get_value();box3.volume();cout<<"volmue of bax3 is ";box3.display();return 0;}第三章2:#include <iostream>using namespace std;class Date{public:Date(int,int,int);Date(int,int);Date(int);Date();void display();private:int month;int day;int year;};Date::Date(int m,int d,int y):month(m),day(d),year(y) { }Date::Date(int m,int d):month(m),day(d){year=2005;}Date::Date(int m):month(m){day=1;year=2005;}{month=1;day=1;year=2005;}void Date::display(){cout<<month<<"/"<<day<<"/"<<year<<endl;}int main(){Date d1(10,13,2005);Date d2(12,30);Date d3(10);Date d4;d1.display();d2.display();d3.display();d4.display();return 0;}3:#include <iostream>using namespace std;class Date{public:Date(int=1,int=1,int=2005);void display();private:int month;int day;int year;};Date::Date(int m,int d,int y):month(m),day(d),year(y) { }void Date::display(){cout<<month<<"/"<<day<<"/"<<year<<endl;}int main(){Date d1(10,13,2005);Date d2(12,30);Date d4;d1.display();d2.display();d3.display();d4.display();return 0;}4:#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void display();private:int num;float score;};void Student::display(){cout<<num<<" "<<score<<endl;}int main(){Student stud[5]={Student(101,78.5),Student(102,85.5),Student(103,98.5), Student(104,100.0),Student(105,95.5)};Student *p=stud;for(int i=0;i<=2;p=p+2,i++)p->display();return 0;}5:#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}int num;float score;};void main(){Student stud[5]={Student(101,78.5),Student(102,85.5),Student(103,98.5), Student(104,100.0),Student(105,95.5)};void max(Student* );Student *p=&stud[0];max(p);}void max(Student *arr){float max_score=arr[0].score;int k=0;for(int i=1;i<5;i++)if(arr[i].score>max_score) {max_score=arr[i].score;k=i;} cout<<arr[k].num<<" "<<max_score<<endl;}6:#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) {num=n;score=s;}void display(){cout<<num<<" "<<score<<endl;} private:int num;float score;};int main(){Student stud(101,78.5);stud.display();stud.change(101,80.5);stud.display();return 0;}7: 解法一#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) {num=n;score=s;}void display() {cout<<num<<" "<<score<<endl;}//可改为:void display() const {cout<<num<<" "<<score<<endl;} private:int num;float score;};int main(){const Studentstud(101,78.5);stud.display();//stud.change(101,80.5);stud.display();return 0;}解法二:#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) const {num=n;score=s;}void display() const {cout<<num<<" "<<score<<endl;}private:mutable int num;mutable float score;};int main(){const Student stud(101,78.5);stud.display();stud.change(101,80.5);stud.display();return 0;}解法三:#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) {num=n;score=s;}void display() {cout<<num<<" "<<score<<endl;} private:int num;float score;};int main(){Student stud(101,78.5);Student *p=&stud;p->display();p->change(101,80.5);p->display();return 0;}8:#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) {num=n;score=s;}void display() {cout<<num<<" "<<score<<endl;} private:int num;float score;};int main(){Student stud(101,78.5);void fun(Student&);fun(stud);return 0;}void fun(Student &stu){stu.display();stu.change(101,80.5);stu.display();}9:#include <iostream>using namespace std;class Product{public:Product(int n,int q,float p):num(n),quantity(q),price(p){};void total();static float average();static void display();private:int num;int quantity;float price;static float discount;static float sum;static int n;};void Product::total(){float rate=1.0;if(quantity>10) rate=0.98*rate;sum=sum+quantity*price*rate*(1-discount);n=n+quantity;}void Product::display(){cout<<sum<<endl;cout<<average()<<endl;}float Product::average(){return(sum/n);}float Product::discount=0.05;float Product::sum=0;int Product::n=0;int main(){Product Prod[3]={Product(101,5,23.5),Product(102,12,24.56),Product(103,100,21.5) };for(int i=0;i<3;i++)Prod[i].total();Product::display();return 0;}10:#include <iostream>using namespace std;class Date;class Time{public:Time(int,int,int);friend void display(const Date &,const Time &); private:int hour;int minute;int sec;};Time::Time(int h,int m,int s){hour=h;minute=m;sec=s;}class Date{public:Date(int,int,int);friend void display(const Date &,const Time &); private:int month;int day;int year;};Date::Date(int m,int d,int y){month=m;day=d;year=y;}void display(const Date &d,const Time &t){cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl; cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;}int main(){Time t1(10,13,56);Date d1(12,25,2004);display(d1,t1);return 0;}11:#include <iostream>using namespace std;class Time;class Date{public:Date(int,int,int);friend Time;private:int month;int day;int year;};Date::Date(int m,int d,int y):month(m),day(d),year(y){ }class Time{public:Time(int,int,int);void display(const Date &);private:int hour;int minute;int sec;};Time::Time(int h,int m,int s):hour(h),minute(m),sec(s){ }void Time::display(const Date &d){cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;cout<<hour<<":"<<minute<<":"<<sec<<endl;}int main(){Time t1(10,13,56);Date d1(12,25,2004);t1.display(d1);return 0;}12:#include <iostream>using namespace std;template<class numtype>class Compare{public:Compare(numtype a,numtype b);numtype max();numtype min();private:numtype x,y;};template <class numtype>Compare<numtype>::Compare(numtype a,numtype b){x=a;y=b;}template <class numtype>numtype Compare<numtype>::max(){return (x>y)?x:y;}template <class numtype>numtype Compare<numtype>::min(){return (x<y)?x:y;}int main(){Compare<int> cmp1(3,7);cout<<cmp1.max()<<" is the Maximum of two integer numbers."<<endl;cout<<cmp1.min()<<" is the Minimum of two integer numbers."<<endl<<endl; Compare<float> cmp2(45.78,93.6);cout<<cmp2.max()<<" is the Maximum of two float numbers."<<endl;cout<<cmp2.min()<<" is the Minimum of two float numbers."<<endl<<endl; Compare<char> cmp3('a','A');cout<<cmp3.max()<<" is the Maximum of two characters."<<endl;cout<<cmp3.min()<<" is the Minimum of two characters."<<endl;return 0;}第四章1:#include <iostream>using namespace std;class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;}double get_real();double get_imag();void display();private:double real;double imag;};double Complex::get_real(){return real;}double Complex::get_imag(){return imag;}void Complex::display(){cout<<"("<<real<<","<<imag<<"i)"<<endl;}Complex operator + (Complex &c1,Complex &c2){return Complex(c1.get_real()+c2.get_real(),c1.get_imag()+c2.get_imag()); }int main(){Complex c1(3,4),c2(5,-10),c3;c3=c1+c2;cout<<"c3=";c3.display();return 0;}2:#include <iostream>using namespace std;class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;}Complex operator+(Complex &c2);Complex operator-(Complex &c2);Complex operator*(Complex &c2);Complex operator/(Complex &c2);void display();private:double real;double imag;};Complex Complex::operator+(Complex &c2){Complex c;c.real=real+c2.real;c.imag=imag+c2.imag;return c;}Complex Complex::operator-(Complex &c2){Complex c;c.real=real-c2.real;c.imag=imag-c2.imag;return c;}Complex Complex::operator*(Complex &c2){Complex c;c.real=real*c2.real-imag*c2.imag;c.imag=imag*c2.real+real*c2.imag;return c;}Complex Complex::operator/(Complex &c2){Complex c;c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); return c;}void Complex::display(){cout<<"("<<real<<","<<imag<<"i)"<<endl;}int main(){Complex c1(3,4),c2(5,-10),c3;cout<<"c1+c2=";c3.display();c3=c1-c2;cout<<"c1-c2=";c3.display();c3=c1*c2;cout<<"c1*c2=";c3.display();c3=c1/c2;cout<<"c1/c2=";c3.display();return 0;}3:#include <iostream> //用VC++时改为∶#include <iostream.h> using namespace std; //用VC++时为取消此行class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;}Complex operator+(Complex &c2);Complex operator+(int &i);friend Complex operator+(int&,Complex &);void display();private:double real;double imag;};Complex Complex::operator+(Complex &c){return Complex(real+c.real,imag+c.imag);}Complex Complex::operator+(int &i){return Complex(real+i,imag);}void Complex::display(){cout<<"("<<real<<","<<imag<<"i)"<<endl;}Complex operator+(int &i,Complex &c){return Complex(i+c.real,c.imag);}int main(){Complex c1(3,4),c2(5,-10),c3;c3=c1+c2;cout<<"c1+c2=";c3.display();c3=i+c1;cout<<"i+c1=";c3.display();c3=c1+i;cout<<"c1+i=";c3.display();return 0;}4:#include <iostream>using namespace std;class Matrix //定义Matrix类{public:Matrix(); //默认构造函数friend Matrix operator+(Matrix &,Matrix &); //重载运算符“+”void input(); //输入数据函数void display(); //输出数据函数private:int mat[2][3];};Matrix::Matrix() //定义构造函数{for(int i=0;i<2;i++)for(int j=0;j<3;j++)mat[i][j]=0;}Matrix operator+(Matrix &a,Matrix &b) //定义重载运算符“+”函数{Matrix c;for(int i=0;i<2;i++)for(int j=0;j<3;j++){c.mat[i][j]=a.mat[i][j]+b.mat[i][j];}return c;}void Matrix::input() //定义输入数据函数{cout<<"input value of matrix:"<<endl;for(int i=0;i<2;i++)for(int j=0;j<3;j++)cin>>mat[i][j];}void Matrix::display() //定义输出数据函数{for (int i=0;i<2;i++){for(int j=0;j<3;j++){cout<<mat[i][j]<<" ";}cout<<endl;}}int main(){Matrix a,b,c;a.input();b.input();cout<<endl<<"Matrix a:"<<endl;a.display();cout<<endl<<"Matrix b:"<<endl;b.display();c=a+b; //用重载运算符“+”实现两个矩阵相加cout<<endl<<"Matrix c = Matrix a + Matrix b :"<<endl;c.display();return 0;}5:#include <iostream.h>//using namespace std;class Matrix{public:Matrix();friend Matrix operator+(Matrix &,Matrix &);friend ostream& operator<<(ostream&,Matrix&);friend istream& operator>>(istream&,Matrix&);private:int mat[2][3];};Matrix::Matrix(){for(int i=0;i<2;i++)for(int j=0;j<3;j++)mat[i][j]=0;}Matrix operator+(Matrix &a,Matrix &b){Matrix c;for(int i=0;i<2;i++)for(int j=0;j<3;j++){c.mat[i][j]=a.mat[i][j]+b.mat[i][j];}return c;}istream& operator>>(istream &in,Matrix &m){cout<<"input value of matrix:"<<endl;for(int i=0;i<2;i++)for(int j=0;j<3;j++)in>>m.mat[i][j];return in;}ostream& operator<<(ostream &out,Matrix &m){for (int i=0;i<2;i++){for(int j=0;j<3;j++){out<<m.mat[i][j]<<" ";}out<<endl;}return out;}int main(){ Matrix a,b,c;cin>>a;cin>>b;cout<<endl<<"Matrix a:"<<endl<<a<<endl;cout<<endl<<"Matrix b:"<<endl<<b<<endl;c=a+b;cout<<endl<<"Matrix c = Matrix a + Matrix b :"<<endl<<c<<endl; return 0;}6:#include <iostream>using namespace std;class Complex{public:Complex(){real=0;imag=0;}Complex(double r){real=r;imag=0;}Complex(double r,double i){real=r;imag=i;}operator double(){return real;}void display();private:double real;double imag;};void Complex::display(){cout<<"("<<real<<", "<<imag<<")"<<endl;}int main(){Complex c1(3,4),c2;double d1;d1=2.5+c1;cout<<"d1="<<d1<<endl;c2=Complex(d1);cout<<"c2=";c2.display();return 0;}7:#include <iostream>using namespace std;class Student{public:Student(int,char[],char,float);int get_num(){return num;}char * get_name(){return name;}char get_sex(){return sex;}void display(){cout<<"num:"<<num<<"\nname:"<<name<<"\nsex:"<<sex<<"\nscore:"<<score<<"\n\n";} private:int num;char name[20];char sex;float score;};Student::Student(int n,char nam[],char s,float so){num=n;strcpy(name,nam);sex=s;score=so;}class Teacher{public:Teacher(){}Teacher(Student&);Teacher(int n,char nam[],char sex,float pay);void display();private:int num;char name[20];char sex;float pay;};Teacher::Teacher(int n,char nam[],char s,float p){num=n;strcpy(name,nam);sex=s;pay=p;}Teacher::Teacher(Student& stud){num=stud.get_num();strcpy(name,stud.get_name());sex=stud.get_sex();pay=1500;}void Teacher::display(){cout<<"num:"<<num<<"\nname:"<<name<<"\nsex:"<<sex<<"\npay:"<<pay<<"\n\n";}int main(){Teacher teacher1(10001,"Li",'f',1234.5),teacher2;Student student1(20010,"Wang",'m',89.5);cout<<"student1:"<<endl;student1.display();teacher2=Teacher(student1);cout<<"teacher2:"<<endl;teacher2.display();return 0;}第五章1:#include <iostream>using namespace std;class Student。

c--面向对象程序设计课后习题解答-谭浩强

c--面向对象程序设计课后习题解答-谭浩强

(5)第6行末尾少了一个分号。 (6)add函数中的retrun拼写错误,应为return。编译系统把retrun作为未声明的标识符而报错 ,因为retrun(z)会被认为是函数调用的形式。 (7)变量a和b未被赋值。 改正后的程序如下: #include using namespace std; int main( {int add(int x,int y; int a,b,c; cin >> a >> b; c=add(a,b; cout <<" a+b=" << c < return 0; } int add(int x,int y {int z; z=x+y; return(z; } 运行情况如下: 5 8↙ 13 10.输入以下程序,编译并运行,分析运行结果。 #include using namespace std; int main( { void sort(int x,int y,int z; int x,y,z;
1 5 3↙ (输入3个整数
1 (输出其中最小的数
8.在你所用的C++系统上,输入以下程序,进行编译,观察编译情况,如果有错误,请修改 程序,再进行编译,直到没有错误,然后进行连接和运行,分析运行结果。
int main( ; { int a,b; c=a+b; cout >>" a+b=" >> a+b; } 【解】 上机编译出错,编译出错信息告知在第2行出错,经检查,发现第1行的末尾多了一个分号,编译 系统无法理解第2行的花括号,导致报告第2行出错。将第1行的末尾的分号去掉,重新编译,编 译出错信息告知在第5行和第6行出错。第5行出错原因是cout未经声明,因为cout不是C++语言 提供的系统的关键字,而是输出流的对象,必须使用头文件iostream。第6行出错原因是main是i nt型函数,应返回一个整型值。将程序改为
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第十五章面向对象编程1。

什么是虚成员?在类中被声明为virtual的成员,基类希望这种成员在派生类中重定义。

除了构造函数外,任意非static成员都可以为虚成员。

2。

给出protected访问标号的定义。

它与private有何不同?protected为受保护的访问标号,protected成员可以被该类的成员、友元和派生类成员(非友元)访问,而不可以被该类型的普通用户访问。

而private成员,只能被基类的成员和友元访问,派生类不能访问。

3。

定义自己的Item_base类版本。

class Item_base{public:Item_base( const string &book = '', double sales_price = 0.0) :isbn( book ), price( sales_price ) { }string book( ) const{return isbn;}virtual double net_price( size_t n ) c onst{return price * n;}virtual ~Item_base() { }private:string isbn;protected:double price;};4。

图书馆可以借阅不同种类的资料—书、CD、DVD等等。

不同种类的借阅资料有不同的登记、检查和过期规则。

下面的类定义了这个应用程序可以使用的基类。

指出在所有借阅资料中,哪些函数可能定义为虚函数,如果有,哪些函数可能是公共的。

(注:假定LibMember 是表示图书馆读者的类,Date是表示特定年份的日历日期的类。

)class Library{public:bool check_out( const LibMember& );bool check_in( cosnt LibMember& );bool is_late( const Date& today );double apply_fine();ostream& print( ostream& = count );Date due_date() const;Date date_borrowed() const;string title() const;const LibMember& member() const;};因为有不同的登记、检查、和过期规则,所以bool check_out( const LibMember& );bool check_in( cosnt LibMember& );bool is_late( const Date& today );double apply_fine();ostream& print( ostream& = count );这几个函数应该被定义为虚函数,print函数可能用于打印不同的项目的内同,也定义为虚函数。

其他几个函数,因为操作都有公共性质,所以应该是公共的。

5。

如果有,下面的声明中哪些是错误的?class Base { …};(a) class Derived : public Derived { … };(b) class Derived : Base { … };(c) class Derived : Private Base { … };(d) class Derived : public Base;(e) class Derived : inherits Base { … };(a) 错误,不能用类本身作为类的基类,(d) 声明类时,不可以包含派生列表。

(e) 派生不能用inherits6。

编写自己的Bulk_item类版本。

class Bulk_item : public item_base{public:double net_price( size_t cnt ) const{if ( cnt > min_qty )return cnt * ( 1- discount ) * price;elsereturn cnt * price;}private:size_t min_qty;double discount;};7。

可以定义一个类型实现有限折扣策略。

这个类可以给低于某个上限的购书量一个折扣,如果购买的数量超过该上限,则超出部分的书应按正常价格购买。

定义一个类实现这种策略。

class Ltd_item : public item_base{public:Ltd_item( const string& book = “”, double sales_price, size_t qty = 0, double disc_rate = 0 ) : item_base( book, sales_price), max_qty( qty ), discount( disc_rate ) { } double net_price( size_t cnt ) const{if ( cnt <= max_qty )return cnt * ( 1- discount ) * price;elsereturn cnt* price – max_qty * discount * price;}private:size_t max_qty;double discount;};8。

对于下面的类,解释每个函数:struct base{string name() { return basename; }// 返回私有成员basenamevirtual void print( ostream &os ) { os << basename; } // 打印私有成员basename private:string basename;};struct derived{void print() { print(ostream &os ); os << ““ << mem; } // 首先调用base类的ptint函数,然后打印一个空格和私有成员memprivate:int mem;};如果该代码有问题,如何修正?问题:没有声明类derived是从base派生过来的,改正为如下:struct base{base( string szNm ): basename( szNm ) { }string name() { return basename; } // 返回私有成员basenamevirtual void print( ostream &os ) { os << basename; } // 打印私有成员basename private:string basename;};struct derived :public base{derived( string szName, int iVal ): base( szName ), mem( iVal ) ( )void print() { print( base :: ostream &os ); os << ““ << mem; }private:int mem;};9。

给定上题中的类和如下对象,确定在运行时调用哪个函数:base bobj; base *bp1 = &base; base &br1 = bobj;derived dobj; base *bp2 = &doboj; base &br2 = dobj;(a) bobj.print();(b) dobj.print();(c) bp1->name();(d) pb2->name();(b) br1.print();(f) br2.print();(a) bobj.print(); 用的是基类的print函数(b) dobj.print(); 用的是派生类的print函数(c) bp1->name(); 用的是基类的name函数(d) pb2->name(); 用的是基类的name函数(b) br1.print(); 用的是基类的print函数(f) br2.print(); 用的是派生类的print函数10。

在15.2.1节的习题中编写一个表示图书馆借阅政策的基类。

假定图书馆提供下列种类的借阅资料,每一种有自己的检查和登记政策。

将这些项目组成一个继承层次:book atdio book recordchildren’s puppet sega video game videocdrom book Nintendo video game rental booksony playstation video game类book、record、children’s puppet、video继承自Library;类audio book ,cdrom book, rental book 继承自类book;类sega video game, Nintendo video game, sony playstation video game继承自类video.11。

在下列包含一族类型的一般抽象中选择一种(或者自己选择一个),将这些类型组织成一个继承层次。

(a) 图像文件格式(如gif, tiff, jpeg, bmp )(b) 几何图元(如矩形,圆,球形,锥形)(c) C++语言的类型(如类,函数,成员函数)对(b)中的几何图元组织成一个继承层次,基类Figure,矩形Rectangle, 圆cicle, 球形sphere,锥形Cone继承自Figure类。

12。

对上题中选择的类,标出可能的虚函数以及public和protected成员。

虚函数,比如计算图形面积的函数virtual double area(); 计算体积的函数virtual double cubage(); 求周长的函数virtual double perimeter();Figuer类的public 成员可能有两个图元的尺寸:xSize, ySize,其他类的protected成员可能有cone类和球形的zSize即Z轴尺寸,还有13。

对于下面的类,列出C1中的成员函数访问ConcreteBase的static成员的所有方式,列出C2类型的对象访问这些成员的所有方式。

struct ConcreteBase{static std::size_t object_count();protected:static std::size_t obj_count;};struct C1 : public ConcreteBase { //… }struct C2 : public ConcreteBase { // … }C1中的成员函数访问基类的static成员可以用( 1) ConcreteBase::成员名(2) C1::成员名(3) 通过C1类对象或对象的引用,使用(. )操作符访问(4) 通过C1类对象的指针,使用箭头(->)操作符访问(5) 直接使用成员名。

相关文档
最新文档