类A对象初始化及成员数据类B对象初始化的构造函数-C程序设计谭浩强

需积分: 7 1 下载量 29 浏览量 更新于2023-12-24 收藏 8.61MB PPT 举报
构造函数和对象成员是C程序设计中非常重要的概念。在谭浩强编著的C程序设计教材中,构造函数与对象成员的初始化是一个关键的概念。在类A中,如果包含了类B的对象,那么在初始化类A的对象的同时还需要对类B的对象进行初始化。这就要求类A的构造函数中需要调用类B的构造函数来完成对成员数据类B的对象的初始化。 在具体的代码示例中,我们可以看到类B和类A的定义如下所示: ``` class B{ .... }; class A{ int x , y; B b1, b2; }; ``` 在类A的定义中,包含了两个类B的对象b1和b2。这意味着在初始化类A的对象时,不仅需要对类A的成员数据x和y进行初始化,还需要对b1和b2进行初始化。这就需要在类A的构造函数中调用类B的构造函数来完成对b1和b2的初始化工作。 C语言作为一种历史悠久的程序设计语言,自1946年第一台电子数字计算机ENIAC问世以来就逐步完善并发展壮大。随着计算机应用领域的不断扩大,计算机技术也得到了高速发展。在这样的背景下,程序设计语言作为应用计算机的工具也得到了不断充实和完善。C语言在20世纪60年代由Martin Richards开发了BCPL语言,之后又由Ken Thompson发明了实用的B语言。最终在1972年由Dennis Ritchie和Brian Kernighan在B语言的基础上发明了C语言,成为了一种极为流行的程序设计语言。 在C程序设计中,构造函数和对象成员的初始化是一个重要的概念,特别是在涉及到类A中包含类B的对象的情况下。理解和掌握这一概念,能够让程序员更好地编写和设计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 上传