8.3 C++类的实现

    类的实现就是定义其成员函数的过程。类的实现有两种方式:一种是在类定义时同时完成成员函数的定义,另一种是在类定义的外部定义其成员函数。

    8.3.1 在类定义时定义成员函数

    成员函数的实现可以在类定义时同时完成,如代码8.2所示。

    代码8.2 在类定义时实现成员函数DefineAndImplement1


    <————————————文件名:example802.h————————————————> 01 #include<iostream> 02 #include<cstring> 03 using namespace std; 04 class computer 05 { 06 private: 07 char brand[20]; 08 float price; 09 public: 10 void print()//在类定义的同时实现了3个成员函数 11 { 12 cout<<"品牌:"<<brand<<endl; 13 cout<<"价格:"<<price<<endl; 14 } 15 void SetBrand(char*sz) 16 { 17 strcpy(brand,sz);//字符串复制 18 } 19 void SetPrice(float pr) 20 { 21 price=pr; 22 } 23 }; <———————————文件名:example802.cpp————————————————> 24 #include"example802.h"//包含了computer类的定义 25 int main() 26 { 27 computer com1;//声明创建一个类对象 28 com1. SetPrice(5000);//调用public成员函数SetPrice()设置price 29 com1. SetBrand("Lenovo");//调用public成员函数SetBrand()设置Brand 30 com1. print();//调用print()函数输出信息 31 return 0; 32 }

    输出结果如下所示。


    品牌:Lenovo 价格:5000

    【代码解析】从代码10~22行可以看出,此时,类computer定义中的成员函数print()、SetBrand()和SetPrice()不再只是原型声明,而是一个完整的函数定义,有函数头、函数体和返回值,当然,成员函数也可以有参数,但和普通的函数相比,类中的成员函数可以访问同类中的private数据成员。

    在类定义的同时定义的成员函数,编译器会自动将其定义为inline函数。而且除特殊指明外,成员函数操作的是同一对象中的数据成员,如代码8.2中的brand和price。