构造函数及对象成员初始化——谭浩强c简单详细版

需积分: 10 6 下载量 73 浏览量 更新于2024-01-02 收藏 8.79MB PPT 举报
构造函数与对象成员 在C++程序设计中,类的构造函数是用来初始化对象的特殊成员函数。构造函数与对象成员之间的关系在谭浩强编著的《C程序设计》中进行了简单详细的介绍。当一个类A的对象初始化的同时,需要对其成员数据类B的对象进行初始化,所以,类A的构造函数中要调用类B的构造函数。这种情况下,类A中包含类B的对象。 例如,在下面给出的代码中,类B和类A的关系非常典型: ``` class B{ .... }; class A{ int x , y; B b1, b2; }; ``` 在这个例子中,类A中包含两个类B的对象b1和b2。因此,在类A的构造函数中需要调用类B的构造函数对b1和b2进行初始化。 对于C++程序设计而言,构造函数与对象成员的关系在实际开发中非常常见。对于类A中包含类B的成员对象,构造函数的正确调用是非常重要的,能够保证对象的正确初始化,避免出现意外的错误。 谭浩强编著的《C程序设计》一书对C++语言的发展历史、概述和程序设计进行了较为全面的介绍。C语言作为应用计算机的一种工具,随着计算机应用领域的不断扩大,在程序设计语言方面也得到了不断的充实和完善。自从1946年第一台电子数字计算机ENIAC问世以来,计算机技术经历了长足的发展,硬件和软件都在不断更新换代。在这种背景下,C语言也在不断发展,逐渐成为了一种优秀的程序设计语言。 C语言的发展历史可以追溯到20世纪60年代,当时Martin Richards开发了BCPL语言,并用于开发系统软件。随后,Ken Thompson在继承BCPL语言的许多优点的基础上发明了实用的B语言。到了1972年,Dennis Ritchie和Brian Kernighan在B语言的基础上发明了C语言,成为了广泛应用的程序设计语言。 总的来说,构造函数与对象成员是C++程序设计中非常重要的一部分。正确的构造函数调用能够保证对象成员的正确初始化,是程序设计中的一项基本技能。谭浩强编著的《C程序设计》提供了对C++语言及其发展历史的全面介绍,对于想要深入了解C++的读者来说是一本不可多得的好书。

优化以下代码:#include <iostream> #include<string.h> using namespace std; class Book { private:     char bookname[30];     char authers[30];     char publishing_house[40];     int pages;     float price; public:     char getbookname();     char getauthers();     char getpublishing_house();     int getpages();     float getprice();          void setbookname(char *a);     void setauthers(char *a);     void setpublishing_house(char *a);     void setpages(int a);     void setprice(float a);     Book(char*a,char*b,cahr*c,int d,float e)     {         strcpy(bookname,a);         strcpy(authers,b);         strcpy(publishing_house,c);         pages=d;         price=e;     } }; char getbookname() {     char*a=bookname;     return a; } char getauthers() {     char*a=authers;     return a; } char getpublishing_house() {     char*a=publishing_house;     return a; } int getpages() {     int a=pages;     return a; } float getprice() {     float a=price;     return a; } void setbookname(char *a) {     strcpy(bookname,a); } void setauthers(char *a) {     strcpy(authers,a); } void setpublishing_house(char *a) {     strcpy(publishing_house,a); } void setpages(int a) {     pages=a; } void setprice(float a) {     price=a; } int main() {      Book a(char a="《C++程序设计》",char b="谭浩强编制",char c="清华大学出版社",d=484,e=36.00);      Book b(char a="《吹牛大王历险记》",char b="拉斯伯等编著",char c="天津人民出版社",d=149,e=12.80);     cout<<a.getbookname()<<"  "<<a.getauthers()<<"  "<<a.getpublishing_house()<<"  "<<"页数:"<<a.getpages()<<"价钱:"<<a.getprice()<<endl;     cout<<b.getbookname()<<"  "<<b.getauthers()<<"  "<<b.getpublishing_house()<<"  "<<"页数:"<<b.getpages()<<"价钱:"<<b.getprice()<<endl;     return 0; }

2023-05-22 上传