记录一次友元权限问题-----无理解

在友元函数定义时。是静态的,因此有以下特点:

所以写友元函数的原则:类的友元函数,传入的参数,只能是其本身的指针。
运行时:类的友元函数还是遵循多态的,所以,友元函数最好还是写在基类中,这样它就可以形成多态了。

总结:编译期,友元函数具有静态特性。运行期,多态

class Base {
public:
    typedef std::shared_ptr<Base> ptr;
friend void visit(Base::ptr m);
protected:
    int b = 0;
private:
    int age = 0;
};
class Derive : public Base {
typedef std::shared_ptr<Derive> ptr;
friend void visitD(Base::ptr);
private:
    int n = 0;
};

派生类的友元函数,不能通过基类指针访问基类的protected成员变量(友元函数不具备继承,传递的特性,同时具备单向性)


fdsa.png
图片.png
class Base {
public:
    typedef std::shared_ptr<Base> ptr;
friend void visit(std::shared_ptr<Derive> m);
protected:
    int b = 1;
private:
    int age = 2;
};

class Derive : public Base {
public:
    typedef std::shared_ptr<Derive> ptr;
friend void visitD(Derive::ptr);
private:
    int n = 3;
};

基类的友元函数,不能通过派生类的指针访问基类的protected 成员


图片.png
class Shape {
public:
    friend bool PointInShape(const Point<double>& cur, std::shared_ptr<const Shape> s);
    friend bool PointOnShape(const Point<double>& cur, std::shared_ptr<const Shape> s);

    enum ShapeType {
        M,
        V,
        CONN,
        Poly,
        UNKNON
    };

    typedef std::shared_ptr<Shape> ptr;
    Shape(std::string& line)
    :m_level(0) {
        static uint64_t s_key = 0;
        m_key = s_key;
        s_key++;
        std::stringstream ss;
        ss << line;
        double x;
        double y;
        while(ss >> x && ss >> y) {
            m_points.push_back(Point<double>(x,y));
        }
    };

    virtual ~Shape(){};

    // plot 内联 ---- 
    void plot() const {
        size_t pNum = m_points.size();
        std::vector<double> x(pNum + 1);
        std::vector<double> y(pNum + 1);
        for(size_t i = 0; i < pNum; ++i) {
            x[i] = (m_points[i].getX());
            y[i] = (m_points[i].getY());
        }
        x[pNum] = (m_points[0].getX());
        y[pNum] = (m_points[0].getY());
        std::string c = getColor();
        plt::plot(x, y, c);
    };

    size_t size() { return m_points.size();};    
    int getLevel() { return m_level;};
    uint64_t getKey() const {return m_key;};


    const Point<double>& operator[] (std::size_t position) const{
        return m_points[position];
    }; 

    std::string ToString() const;
protected:
    virtual const std::string getColor() const = 0;
    std::vector<Point<double>> m_points;
    int m_level = 0;
    uint64_t m_key = 0;
};

为什么PointInShape报错。


图片.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 参考链接: https://light-city.club/sc/ https://chenxiaowei.git...
    雪上霜阅读 504评论 0 0
  • 技术交流QQ群:1027579432,欢迎你的加入! 一.static关键字的作用 1.静态成员的特点 1.sta...
    CurryCoder阅读 2,903评论 3 3
  • 面向对象的程序设计思想是什么?答:把数据结构和对数据结构进行操作的方法封装形成一个个的对象。 什么是类?答:把一些...
    飞扬code阅读 2,755评论 0 11
  • c++17入门经典 chapter11 类 定义类 class ClassName { }; 类的所有成员是默认私...
    太岁_58c4阅读 553评论 0 0
  • 类成员的访问权限 继承方式 派生类的成员(及友元)对基类成员的访问权限只与基类中的访问说明符有关。派生列表中访问说...
    安然_fc00阅读 1,145评论 0 1