实验五 构造函数和析构函数30.docVIP

  • 15
  • 0
  • 约3.39千字
  • 约 6页
  • 2018-05-02 发布于贵州
  • 举报
实验五 构造函数和析构函数30

实验五 构造函数和析构函数 实验目的 掌握类的构造函数的定义方法、构造函数的重载、析构函数的定义方法、掌握对象数据成员的初始化方法。深刻领会构造函数和析构函数被调用的时间和特性,以及它们在程序中的作用。 实验内容 自定义一个类,并在其构造函数和析构函数中编写一段输出代码,在主函数中定义一个类的对象,然后输出字符串“This is a C++ Program.”,测试构造函数和析构函数何时被调用。 // 123.cpp : 定义控制台应用程序的入口点。 // #include stdafx.h #includeiostream using namespace std; class test { public: test() { coutconstructer calledendl; }; void display() { coutThis is a C++ Program.endl; } ~test() { coutdestructer calledendl; } }; int _tmain(int argc, _TCHAR* argv[]) { test test1; test1.display(); return 0; } (2) 以下是产品类Product的定义,但没有类的实现部分,请根据注释中类的定义编写类的实现部分的代码,并编写相应的对所定义的类进行测试的程序。 Class Product { Private: char *name; //产品名称 int price; //产品单价 int quantity; //产品剩余量 public: Product(char *a,int b,int c); //构造函数 void purchase(int money); //购买产品 void remain() //显示剩余产品数量 ~Product(); //析构函数 }; // 123.cpp : 定义控制台应用程序的入口点。 // #include stdafx.h #includeiostream #includestring using namespace std; class product {private: string name; //产品名称 int price; //产品单价 int quantity; //产品剩余量 public: int quantity1; product(string a,int b,int c) { name=a; price=b; quantity=100; quantity=quantity-c; quantity1=c; } void purchase() { coutmoney=price*quantity1endl; }//购买产品 void remain() { coutquantityendl; }//显示剩余产品数量 ~product() { coutdestructer calledendl; } }; int _tmain(int argc, _TCHAR* argv[]) { product pro1(abc,10,20); pro1.purchase(); pro1.remain(); return 0; } (3) 以下是图书类Book的定义,但没有类的实现部分,请根据注释补充完整,并编写相应的对所定义的类进测试的程序。 class Book { private: char *name; //书名 int *author; //作者 int sale; //销售量 public: Book(); //默认构造函数; Book(char *a,char *b,int c); //构造函数 void print(); //输出函数 ~Book(); //析构函数 }; // 123.cpp : 定义控制台应用程序的入口点。 // #include stdafx.h #includeiostream #includestring using namespace std; //以下是图书类Book的定义,但没有类的实现部分,请根

文档评论(0)

1亿VIP精品文档

相关文档