6——在类的外部定义成员函数
在类定义的外部定义成员函数时,应使用作用域操作符(::)来标识函数所属的类。
即有如下形式:
返回类型 类名::成员函数名(参数列表)
{
函数体
}
其中,返回类型、成员函数名和参数列表必须与类定义时的函数原型一致。
//Computer.h
class Computer //类定义,起到接口作用 { private: char brand[20]; float price; public: //3个public成员函数的原型声明 void print(); void SetBrand(char * sz); void SetPrice(float pr); };
#include "Computer.h" //包含computer类定义
#include <iostream>
#include <cstring>
using namespace std;
void computer::print() //成员函数的实现,注意作用域限定符的使用
{
cout << "品牌:" << brand << endl;
cout << "价格:" << price << endl;
}
void computer::SetBrand(char * sz)
{
strcpy(brand, sz); //字符串复制
}
void computer::SetPrice(float pr)
{
price = pr;
}
int main()
{
computer com1; //声明创建一个类对象
com1.SetPrice(5000); //调用public成员函数SetPrice设置price
com1.SetBrand("Lenovo"); //调用public成员函数SetBrand设置Brand
com1.print(); //调用print()函数输出信息
return 0;
}

浙公网安备 33010602011771号