c++ - 如何为包含该类的非引用/指针的类定义朋友成员函数?
问题描述
如果我有两个类:一个是Point
,第二个是Square
,有Point
成员数据:那些是“私有的”来表示点的坐标。x
y
类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;
}
}
解决方案
推荐阅读
- file-descriptor - 文件描述符规范
- gerrit - 有没有办法在 Gerrit 中添加替代修复?
- javascript - 从 ReactJS 中的对象列表渲染 JSON 子列表
- sql - 从 SQL 中的每一列中减去聚合函数
- magento - Magento SOAP API - 获取产品附件
- json - Power BI 自定义主题 .json - 多系列自定义
- amazon-web-services - 订阅者的数量是否会影响 MQTT 中的接收时间?
- python - 如何处理 ElementNotInteractableException 硒
- c# - 使用预编译视图部署到 IIS 时的 MapRequestHandler 问题
- azure - 在 Azure 中使用不同的配置创建多个 VM