首页 > 解决方案 > 如何为包含该类的非引用/指针的类定义朋友成员函数?

问题描述

如果我有两个类:一个是Point,第二个是Square,有Point成员数据:那些是“私有的”来表示点的坐标。xy

Square和类似的类实现“has-a”关系;所以例如Square有四个点。出于某种原因Point,通过“友谊”授予对其私人数据的访问权限;但仅限于调用print包含类的成员函数。

问题:

该类Point需要查看类的定义,Square以便将它们的打印成员声明为朋友。

Square需要查看类的定义,Point以便它可以将它的实例声明为其成员。

使用前向声明不会解决问题,因为它仍然是“不完整类型”。那么如何解决呢?

class Square;
class Point{
    public:
        using pos = int;

        Point() = default;
        Point(pos, pos);

        pos getX()const{ return x_; }
        pos getY()const{ return y_; }
        void setX(pos x){ x_ = x; }
        void setY(pos y){ y_ = y; }

    private:
        pos x_{};
        pos y_{};

        // friend void Square::print()const; // the problem here. Square is still incomplete type
        // friend class Square; // we don't want this solution
};

inline Point::Point(pos x, pos y) :
    x_{ x },
    y_{ y }{

}

class Square{
    public:
        Square(const Point&, const Point&, const Point&, const Point&);

        Point getPtA()const{ return ptA_; }
        Point getPtB()const{ return ptB_; }
        Point getPtC()const{ return ptC_; }
        Point getPtD()const{ return ptD_; }
        void setPtA(const Point& ptA){ ptA_ = ptA; }
        void setPtB(const Point& ptB){ ptB_ = ptB; }
        void setPtC(const Point& ptC){ ptC_ = ptC; }
        void setPtD(const Point& ptD){ ptD_ = ptD; }

        void print()const;

    private:
        Point ptA_, ptB_, ptC_, ptD_;
};

Square::Square(const Point& ptA, const Point& ptB, const Point& ptC, const Point& ptD) :
    ptA_{ ptA }, ptB_{ ptB },
    ptC_{ ptC }, ptD_{ ptD }{

}

void Square::print()const{
    using pos = Point::pos;

    for(pos i{ptA_.x_}; i != ptB_.x_; ++i){
        for(pos j{ptA_.y_}; j != ptC_.y_; ++j)
            std::cout << "*";
        std::cout << std::endl;
    }
}

标签: c++friend

解决方案


推荐阅读