第十一章:使用类

1、运算符重载   operator+  (take '+' for example)

  (1) 重载后必须至少有一个用户定义的操作数(struct class etc...),防止把一个C++标准的‘-’重载成'+'

  (2) 不能违反运算符原来的句法规则; 例如不能将'%'重载成一个操作数

    (3) 不能创建新运算符

    (4) 有些运算符不能重载    sizeof   ?:    .   .*     ::   etc....

  (5) 有些运算符只能通过成员函数重载   =   ()   []   ->

2、友元

  (1) friend XXX operator+(xxx,xxx);  运算符重载,非成员函数,但是可以访问私有成员; 

  常用的友元:重载<<操作符  (常用的cout就是ostream类对<<重载过来的,)

  test_code:

  #include <iostream>
  using namespace::std;

class Time{
private:
  int min;
  int hour;
public:
  Time(int n,int m);
  friend ostream& operator<<(ostream & os, const Time & t);        //BTW: ostream处必须为引用;返回值为ostream& 保证可以实现cout << "xxx" << t << "xx"的语句
};

Time::Time(int n,int m){
  min = n;
  hour = m;
}

ostream& operator<<(ostream & os, const Time& t){
  os << t.hour << "hours. " << t.min << "minutes" ;

  return os;

}


int main(void){
  Time test(5,6);
  cout << "haha "  <<  test;
}

##print:haha 6hours.5minutes

(2)成员函数与非成员函数的一个小差别

  class Time{};

  Time operator+(const Time& t);

  friend Time operator+(const time & t1,const time & t2);

3、类的转换

  TBD 

 

转载于:https://www.cnblogs.com/uudog/p/4117836.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值