5——类的实现
类的实现就是定义其成员函数的过程,
类的实现有两种方式:
1>在类定义时同时完成成员函数的定义。
2>在类定义的外部定义其成员函数。
在类的内部定义成员函数:
#include <iostream>
#include <cstring>//C++版的string头文件
using namespace std;
class computer
{
public: //在类定义的同时实现了3个成员函数
void print()
{
cout << "品牌:" << brand << endl;
cout << "价格:" << price << endl;
}
void SetBrand(char * sz)
{
strcpy(brand, sz); //字符串复制
}
void SetPrice(float pr)
{
price = pr;
}
private:
char brand[20];
float price;
};
#include "example802.h" //包含了computer类的定义
int main()
{
computer com1; //声明创建一个类对象
com1.SetPrice(5000); //调用public成员函数SetPrice设置price
com1.SetBrand("Lenovo"); //调用public成员函数SetBrand设置Brand
com1.print(); //调用print()函数输出信息
return 0;
}

浙公网安备 33010602011771号