设为首页 加入收藏

TOP

C++重载运算符和标准模板库实例讲解(二)
2018-05-26 14:13:59 】 浏览:409
Tags:重载 运算 符和 标准 模板 实例 讲解
然后return该对象 *i++ 先创建临时对象Temp 把原始值赋值给Temp 然后对Temp的数据+1 return Temp *两种加法产生的效果一样 *后加会添加一个形参int 用于区分前加还是后加 并无实际作用 operator++( int ) */ }; int main() { Time T1(11, 59), T2(10,40); ++T1; // T1 加 1 T1.displayTime(); // 显示 T1 ++T1; // T1 再加 1 T1.displayTime(); // 显示 T1 T2++; // T2 加 1 T2.displayTime(); // 显示 T2 T2++; // T2 再加 1 T2.displayTime(); // 显示 T2 return 0; } /*当上面的代码被编译和执行时,它会产生下列结果: *12点0分 *12点1分 *10点41分 *10点42分 */

⑤:赋值运算符重载

#include
          
           
using namespace std;
class Time//时间类
{
private:
 int month;
 int day;
 int hour;
 int minute;
public:
 Time(int mon,int d,int h,int m){//含参构造函数
  month=mon;
  day=d;
  hour=h;
  minute=m;}
 Time(){month=day=hour=minute=0;//无参构造函数
 }
 void display(){
  cout<
           
            

⑥:函数调用运算符() 下标运算符 [] 重载 【只能用成员函数重载 不能用友元函数重载】

#include 
             
              
using namespace std;

class Distance
{
private:
int feet; // 0 到无穷
int inches;  // 0 到 12
public:
// 所需的构造函数
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// 重载函数调用运算符
Distance operator()(int a, int b, int c)
{
Distance D;
// 进行随机计算
D.feet = a + c + 10;
D.inches = b + c + 10 ;
return D;
}
// 显示距离的方法
void displayDistance()
{
cout << "F: " << feet <<  " I:" <<  inches << endl;
}

};
int main()
{
Distance D1(11, 10), D2;

cout << "First Distance : ";
D1.displayDistance();

D2 = D1(10, 10, 10); // invoke operator()
cout << "Second Distance :";
D2.displayDistance();

return 0;
}
/*当上面的代码被编译和执行时,它会产生下列结果:

First Distance : F: 11 I:10
Second Distance :F: 30 I:30*/
             
//重载[]运算符
#include <iostream>  
using namespace std;  
const int SIZE = 10;  
  
class safearay  
{  
   private:  
      int arr[SIZE];  
   public:  
      safearay()   
      {  
         register int i;  
         for(i = 0; i < SIZE; i++)  
         {  
           arr[i] = i;  
         }  
      }  
      int& operator[](int i)  
      {  
          if( i > SIZE )  
          {  
              cout << "索引超过最大值" <<endl;   
              // 返回第一个元素  
              return arr[0];  
          }  
          return arr[i];  
      }  
};  
int main()  
{  
   safearay A;  
  
   cout << "A[2] 的值为 : " << A[2] <<endl;  
   cout << "A[5] 的值为 : " << A[5]<<endl;  
   cout << "A[12] 的值为 : " << A[12]<<endl;  
  
   return 0;  
}  
/* 
A[2] 的值为 : 2 
A[5] 的值为 : 5 
A[12] 的值为 : 索引超过最大值 
0 
*/  
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++结合TCP/IP协议 实现客户端和.. 下一篇著名的C/C++框架和第三方库总结

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目