zoukankan      html  css  js  c++  java
  • C++友元函数和友元类示例

    #include "math.h"
    #include<iostream> 
    using namespace std; 
    
    class Point 
    { 
    public: 
        Point(double xx, double yy) 
        {
            x=xx; 
            y=yy; 
        }
        void Getxy(); 
        friend double Distance(Point &a, Point &b);        //类Point的友元函数
        friend class Yao;                //类Point的友元类
    private: 
        double x, y; 
    }; 
    
    
    class Yao
    {
    public:
        double Multi(Point &a)
        {
            return a.x * a.y + 1;
        }
    };
    
    
    
    void Point::Getxy() 
    { 
        cout<<"("<<x<<","<<y<<")"<<endl; 
    } 
    double Distance(Point &a, Point &b)            //类Point的友元函数
    { 
        double dx = a.x - b.x; 
        double dy = a.y - b.y; 
        return sqrt(dx*dx+dy*dy); 
    } 
    int main(void) 
    { 
        Point p1(3.0, 4.0), p2(6.0, 8.0); 
        p1.Getxy(); 
        p2.Getxy(); 
        double d = Distance(p1, p2);            //Distance是类Point的友元函数,不是成员函数
        cout<<"Distance is "<<d<<endl; 
        Yao yao;
        d = yao.Multi(p1);
        cout<<"Math.Multi is "<<d<<endl;
        return true;
    }

    友元的使用并不复杂,且缺了这玩意完全可以实现,但既然这么设计,就有它存在的合理性,在某些条件下使用它还是很方便的。另外需要注意的一点,编程时,滥用这个东西容易引起数据的安全问题,故需谨慎使用之。

  • 相关阅读:
    md5
    表空间
    create_index
    非额度合同和额度合同
    如何在linux中查找python安装包的路径
    Golang中的SingleFlight与CyclicBarrier
    linux安装protoc
    protobuf 的优缺点
    Xshell 连接 VirtualBox
    限制 input 输入框只能输入纯数字
  • 原文地址:https://www.cnblogs.com/Roarsun/p/2835813.html
Copyright © 2011-2022 走看看