C++ Primer Plus学习:第十一章 使用类(2)

本文详细介绍了C++中的友元函数概念及其应用,并通过示例展示了如何重载输出运算符来实现矢量的输出显示。同时,还提供了一个矢量类的实现,包括矢量的加减乘除等基本运算。
友元
  创建友元函数 原型放在类声明中 friend Time operator*(double m,const Time &t);
  编写函数定义
重载<<
  ostream & operator<<(ostream & os,const c_name & obj) {     os<<...;//display object contents     return os; }
  eg

    mytime3.h

#ifndef MYTIME3_H_
#define MYTIME3_H_
#include <iostream>

class Time
{
      private:
              int hours;
              int minutes;
      public:
             Time();
             Time(int h,int m = 0);
             void AddMin(int m);
             void AddHr(int h);
             void Reset(int h = 0,int m = 0);
             Time operator+(const Time & t)const;
             Time operator-(const Time & t)const;
             Time operator*(double n)const;
             //friend operator* 
             friend Time operator*(double m,const Time & t)
             {
                    return t*m;
                    }
             //friend <<
             friend std::ostream & operator<<(std::ostream & os,const Time & t); 
      } ;
#endif


    mytime3.cpp

#include "mytime3.h"

Time::Time()
{
            hours = minutes = 0;
            } 

Time::Time(int h,int m)
{
               hours = h;
               minutes = m;
               }
               
void Time::AddMin(int m)
{
     minutes += m;
     hours += minutes/60;
     minutes %= 60;
     }
     
void Time::AddHr(int h)
{
     hours += h;
     }
     
void Time::Reset(int h,int m)
{
     hours = h;
     minutes = m;
     }

Time Time::operator+(const Time & t)const
{
     Time sum;
     sum.minutes = minutes + t.minutes;
     sum.hours = hours + t.hours + sum.minutes/60;
     sum.minutes %= 60;
     return sum;
     }
     
Time Time::operator-(const Time & t)const
{
     Time diff;
     int tot1,tot2;
     tot1 = t.minutes + 60*t.hours;
     tot2 = minutes + 60*hours;
     diff.minutes = (tot2-tot1)%60;
     diff.hours = (tot2-tot1)/60;
     return diff;
     }
     
Time Time::operator*(double mult)const
{
     Time result;
     long totalminutes = hours*mult*60 + minutes*mult;
     result.hours = totalminutes/60;
     result.minutes = totalminutes%60;
     return result;
     }


std::ostream & operator<<(std::ostream & os,const Time & t)
{
             os<<t.hours<<" hours, "<<t.minutes<<" minutes.";
             return os;
             }
             


    usetime3.cpp

#include <iostream>
#include "mytime3.h"

int main()
{
    using std::cout;
    using std::endl;
    Time aida(3,35);
    Time tosca(2,48);
    Time temp;
    
    cout<<"Aida and Tosca:\n";
    cout<<aida<<"; "<<tosca<<endl;
    temp = aida + tosca;
    cout<<"Aida + Tosca: "<<temp<<endl;
    temp = aida*1.17;
    cout<<"Aida*1.17: "<<temp<<endl;
    cout<<"10*Tosca: "<<10*tosca<<endl;
    
    system("pause");
    return 0;
    }


矢量
  表示方法
    大小(长度)、方向(角度)
    X,Y
  定义
    namespace VECTOR {     }//end namespace VECTOR
  eg

    vector.h

#ifndef VECTOR_H_
#define VECTOR_H_

#include <iostream>

namespace VECTOR
{
          class VECTOR
          {
                private:
                        double x;
                        double y;
                        double mag;
                        double ang;
                        char mode;
                        void set_mag();
                        void set_ang();
                        void set_x();
                        void set_y();
                  public:
                         Vector();
                         Vector(double n1,double n2,char form = 'r');
                         void set(double n1,double n2,char form = 'r');
                         ~Vector();
                         double xval()const{return x;}
                         double yval()const{return y;}
                         double magval()const{return mag;}
                         double angval()const{return ang;}
                         void polar_mode();
                         void rect_mode();
                         
                         //operator overloading
                         Vector operator+(const Vector & b)const;
                         Vector operator-(const Vector & b)const; 
                         Vector operator-()const;
                         Vector operator*(double n)const; 
                         
                         //friends
                         friend Vector operator*(double n,const Vector & a);
                         friend std::ostream & operator<<(std::ostream & os,const Vector & a);
                };
          }//end namespace VECTOR
#endif


    vector.cpp

#include <cmath>
#include "vect.h"

using std::sin;
using std::cos;
using std::atan2;
using std::cout;

namespace VECTOR
{
          const double Rad_to_deg = 57.2957795130823;
          
          void Vector::set_mag()
          {
               mag = sqrt(x*x + y*y);
               }
               
          void Vector::set_ang()
          {
               if(x == 0.0 && y == 0.0)
                    ang = 0.0;
               else
                   ang = atan2(y,x);
               }
          
          void Vector::set_x()
          {
               x = mag*cos(ang);
               }
               
          void Vector::set_y()
          {
               y = mag*sin(ang);
               }
               
          Vector::Vector()
          {
                          x = y = mag = ang = 0.0;
                          mode = 'r';
                          }     
                          
          Vector::Vector(double n1,double n2,char form)
          {
                                mode = form;
                                if(form == 'r')
                                {
                                        x = n1;
                                        y = n2;
                                        set_mag();
                                        set_ang();
                                        }
                                else if(form == 'p')
                                {
                                     mag = n1;
                                     ang = n2/Rad_to_deg;
                                     set_x();
                                     set_y();
                                     }
                                else
                                {
                                    cout<<"Incorrect 3rd argument to Vector()--";
                                    cout<<"vector set to 0\n";
                                    x = y = mag = ang = 0.0;
                                    mode = 'r';
                                    }
                                }
          
          void Vector::set(double n1,double n2,char form)
          {
               mode = form;
               if(form == 'r')
               {
                       x = n1;
                       y = n2;
                       set_mag();
                       set_ang();
                       
                       }
               else if(form == 'p')
               {
                    mag = n1;
                    ang = n2/Rad_to_deg;
                    set_x();
                    set_y();
                    
                    }
               else
               {
                   cout<<"Incorrect 3rd argument to Vector()--";
                   cout<<"vector set to 0\n";
                   x = y = mag = ang = 0.0;
                   mode = 'r';
                   }
               }
          
          Vector::~Vector()
          {
                           
                           }
                           
          void Vector::polar_mode()
          {
               mode = 'p';
               }
          
          void Vector::rect_mode()
          {
               mode = 'r';
               }
               
          Vector Vector::operator+(const Vector & b)const
          {
                 return Vector(x+b.x,y+b.y);
                 }
          
          Vector Vector::operator-(const Vector & b)const
          {
                 return Vector(x-b.x,y-b.y);
                 }
                 
          Vector Vector::operator-()const
          {
                 return Vector(-x,-y);
                 }
          
          Vector Vector::operator*(double n)const
          {
                 return Vector(n*x,n*y);
                 }
                 
          Vector operator*(double n,const Vector & a)
          {
                 return a*n;
                 } 
          
          std::ostream & operator<<(std::ostream & os,const Vector & v)
          {
                       if(v.mode == 'r')
                               os<<"(x,y) = ("<<v.x<<", "<<v.y<<")";
                       else if(v.mode == 'p')
                       {
                            os<<"(m,a) = ("<<v.mag<<", "<<v.ang*Rad_to_deg<<")";
                            }
                       else
                           os<<"Vector object mode is invalid";
                       return os;
                       }
               }//end namespace VECTOR


    randwalk.cpp

#include <iostream>
#include <ctime>
#include "vect.h"


int main()
{
    using namespace std;
    using VECTOR::Vector;
    srand(time(0));
    double direction;
    Vector step;
    Vector result(0.0,0.0);
    unsigned long steps = 0;
    double target;
    double dstep;
    cout<<"Enter target distance (q to quit):";
    while(cin>>target)
    {
                      cout<<"Enter step length:";
                      if(!(cin>>dstep))
                                       break;
                      while(result.magval()<target)
                      {
                                                   direction = rand()%360;
                                                   step.set(dstep,direction,'p');
                                                   result = result = step;
                                                   steps++;
                                                   }
                      cout<<"After "<<steps<<" steps,the subject has the following location:\n";
                      cout<<result<<endl;
                      result.polar_mode();
                      cout<<" or\n"<<result<<endl;
                      cout<<"Average outward distance per step = "<<result.magval()/steps<<endl;
                      steps = 0;
                      result.set(0.0,0.0);
                      cout<<"Enter target distance (q to quit):"; 
                      }
                      
    cout<<"Bye!--------\n";
    
    system("pause");
    return 0;
    }


Note
  只有在类声明中的原型中才能使用friend关键字
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值