首页 编程C/C++传递对象的练习

传递对象的练习

#include <iostream>
using namespace std;

class cat
{
public:
 cat();
 cat(int,int,int);
 cat(cat &);
 ~cat();
 void setage(int x)
 {
  cout<<“执行setage函数设置为:”<<x<<endl;
  itsage=x;
 }
 void setweight(int x)
 {
  cout<<“执行setweight函数设置为:”<<x<<endl;
  itsweight=x;
 }
 void setheight(int x)
 {
  cout<<“执行setheight函数设置为:”<<x<<endl;
  itsheight=x;
 }
 int getage ()
 {
  cout<<“执行getage函数返回itsage:”<<itsage<<endl;
  return itsage;
 }
 int getweight()
 {
  cout<<“执行getweight函数返回itsweight:”<<itsweight<<endl;
  return itsweight;
 }
 int getheight()
 {
  cout<<“执行getheight函数返回itsheight:”<<itsheight<<endl;
  return itsheight;
 }
private:
 int itsage;
 int itsweight;
 int itsheight;
};
 cat::cat():
 itsage(5),
 itsweight(3),
 itsheight(10)
 {
 cout<<“默认构造函数调用中,初始化对象。。。”<<endl;
 }
 cat::cat(int x,int y,int z)
 {
 cout<<“cat类的重载构造函数,设置三个成员变量的值。。。”<<endl;
 itsage=x;
 itsweight=y;
 itsheight=z;
 }
 cat::cat(cat &thecat)
 {
  cout<<“复制构造函数运行中。。。按引用传递对象。。。”<<endl;
  itsage=thecat.getage();
  itsweight=thecat.itsweight;
  itsheight=thecat.getheight();
 }

 cat::~cat()
 {
  cout<<“析构函数调用中。。。”<<endl;
 }
void show(cat *);
void main()
{
 cout<<“main主函数开始执行。。。”<<endl;
 cat frisky;
 show(&frisky);
 cat frisky2(4,5,6);
 show(&frisky2);
 cat frie(frisky);
 show(&frie); 
 cat *mycat=new cat(1,3,5);
 show(mycat);
 delete mycat;
 mycat=0;
 cat catone;
 catone=frisky;
 show(&catone);

 cout<<“main主函数执行结束!”<<endl;
}
void show(cat *rhs)
{
 cout<<“show函数调用中,打印对象的值。。。”<<endl;
 int a,w,h;
 a=rhs->getage();
 w=rhs->getweight();
 h=rhs->getheight();
 cout<<a<<endl;
 cout<<w<<endl;
 cout<<h<<endl;
 cout<<“show函数之行结束!”<<endl;
}