zoukankan      html  css  js  c++  java
  • [C++]C++学习笔记(三)

    1,运算符重载 示例程序如下:

    1. #ifndef MYTIME1_H_  
    2. #define MYTIME1_H_  
    3.   
    4. class Time  
    5. {  
    6. private:  
    7.     int hours;  
    8.     int minutes;  
    9. public:  
    10.     Time(int h, int m = 0);  
    11.     Time operator+(const Time & t) const;  
    12.     void Show() const;  
    13. };  
    14. #endif  
    15.   
    16.   
    17. Time::Time(int h, int m )  
    18. {  
    19.     hours = h;  
    20.     minutes = m;  
    21. }  
    22.   
    23. Time Time::operator+(const Time & t) const  
    24. {  
    25.     Time sum;  
    26.     sum.minutes = minutes + t.minutes;  
    27.     sum.hours = hours + t.hours + sum.minutes / 60;  
    28.     sum.minutes %= 60;  
    29.     return sum;  
    30. }  
    31.   
    32. void Time::Show() const  
    33. {  
    34.     std::cout << hours << " hours, " << minutes << " minutes";  
    35. }  
    36.   
    37. int main()  
    38. {  
    39.     using std::cout;  
    40.     using std::endl;  
    41.     Time coding(2, 40);  
    42.     Time fixing(5, 55);  
    43.     Time total;  
    44.     total = coding + fixing;  
    45.     // operator notation  
    46.     cout << "coding + fixing = ";  
    47.     total.Show();  
    48.     cout << endl;  
    49.     return 0;  
    50. }  

    2友元函数 通过让函数称为类的友元,可以赋予该函数与类的成员函数相同的访问权限 创建友元函数 1,将函数声明放在类的声明中,并再原型前面加上关键字friend  friend Time operator*(double m,const Time &t); 2,编写友元函数的定义,编写定义的时候不需要在前面加上friend关键字,也不需要类限定符Time:: 总之,类的友元函数是非成员函数,其访问权限和成员函数相同

  • 相关阅读:
    初探element+vue+vue-router
    git命令移动文件夹到另一文件夹
    javascript最大公约数与最小公倍数
    求1-100数字的和
    [摘录]代码优化规则
    基于.NET平台常用的框架和开源程序整理
    软件架构师的12项修炼
    Service Oriented Architecture and WCF 【转】
    电商网站的初期技术选型【转】
    论SOA架构的几种主要开发方式【转】
  • 原文地址:https://www.cnblogs.com/zhiliao112/p/4069201.html
Copyright © 2011-2022 走看看