zoukankan      html  css  js  c++  java
  • 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;
     }  
    

      

  • 相关阅读:
    yum提示Another app is currently holding the yum lock
    函数参数返回值作用域笔记
    递归内置函数笔记
    装饰器笔记
    函数笔记扩展
    集合笔记
    线程和进程
    函数笔记
    线程与进程的区别
    Ubuntu操作及各种命令笔记.txt
  • 原文地址:https://www.cnblogs.com/Burgess-Fan/p/7049855.html
Copyright © 2011-2022 走看看