• C++友元


    View Code
    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    using namespace std;
    
    #define P(x) (x)*(x)
    
    class Point {
        friend class B;
    public:
        Point(double x=0,double y=0) {
            X = x;
            Y = y;
        }
        Point(Point &a);
        double get_x();
        double get_y();
        friend double dis(Point &a,Point &b);
    private:
        double X,Y;
    };
    
    Point::Point(Point &a) {
        X = a.X;
        Y = a.Y;
    }
    
    class B {
    public:
        void reset(int,int);
        B(Point &a);
        void showset();
    private:
        Point val;
    };
    
    B::B(Point &a) {//B是Point的友元所以可以用Point的内容,以下同理
        val.X = a.X;
        val.Y = a.Y;
    }
    
    void B::reset(int x=0,int y=0) {
        val.X = x;
        val.Y = y;
    }
    
    void B::showset() {
        cout << val.get_x() << " " << val.get_y() << endl;
    }
    
    double dis(Point &a,Point &b){
        return sqrt(P(a.X - b.X) + P(a.Y - b.Y));
    }
    
    //double mydis(Point &a,Point &b){//不是友元则不能访问类的私有成员
    //    return sqrt(P(a.X - b.X) + P(a.Y - b.Y));
    //}
    
    double Point::get_x() {
        return X;
    }
    
    double Point::get_y() {
        return Y;
    }
    
    int main() {
        Point s,t(3,4);
        B ans(t);
        cout << s.get_x() << " " << s.get_y() << endl;
        cout << t.get_x() << " " << t.get_y() << endl;
        cout << "dis:" << dis(s,t) << endl;
        ans.showset();
        ans.reset(100,200);
        ans.showset();
        return 0;
    }
  • 相关阅读:
    动态规划01背包
    动态规划矩阵连乘
    分治法归并排序
    动态规划最长公共子序列
    贪心算法活动安排
    分治法二分查找
    vue 可拖拽可缩放 vuedraggableresizable 组件常用总结
    rifilter in python discussed in 3delight
    3delight linear work flow
    pixar stereo rendering doc
  • 原文地址:https://www.cnblogs.com/gray035/p/2993250.html
Copyright © 2020-2023  润新知