【问题标题】:Cannot access friend class's private members无法访问朋友班的私人成员
【发布时间】:2013-02-28 20:01:41
【问题描述】:

有人介意帮助我解决 C++ 链接/编码难题吗?

我有一个形状类。 Shape 需要使用类 Center 的私有数据成员,x 和 y 坐标。我声明朋友类Shape;然后 #include "center.h" 在 Shape.h 中。在 Shape.cpp 中,我定义了我的 ostream& operator

当我尝试编译 Shape.cpp 时,我会遇到这些数据变量的访问错误,例如我没有将 Shape 声明为友元类。我感觉这与编译时的链接顺序有关。我该如何解决这个问题?

#ifndef CENTER_H
#define CENTER_H

class Center
{
    public:
        Center(double x, double y) { xCord = x; yCord = y; }
            // constructor
        friend class Shape;
            // allow Shape to use Center's x and y values

    private:
        double xCord;
            // X-coordinate
        double yCord;
            // Y-coordinate
};

#endif

#ifndef SHAPE_H
#define SHAPE_H

#include "center.h"
#include <iostream>
using namespace std;

class Shape
{
    public:
        Shape(double x, double y) : s_center(x, y) {}
            // constructor
        void moveCenter();
            // moves the center of the shape
        friend ostream& operator<< (ostream& ostr, const Center& c);
            // allows the printing of the Center object

        virtual void printCenter();
            // returns the center of the shape
        virtual double printArea();
            // returns the area of the shape

        virtual bool checkSurface(Shape& s) = 0;
            // checks if the shape can fit into
            // a given surface
        virtual double findArea() = 0;
            // calculates the area of the shape

    private:
        Center s_center;
            // center of the shape
};

#endif

// in shape.cpp
ostream& operator<< (ostream& ostr, const Center& c)
{
    ostr << "(" << c.xCord << ", " << c.yCord << ")";
    return ostr;
}

【问题讨论】:

  • 为什么operator&lt;&lt;(ostream&amp;,const Center&amp;) 会成为Shape 的朋友?
  • 好点。我已将其移至 Center 类。感谢您指出这一点。

标签: c++ header private friend


【解决方案1】:

根据 C++11 标准的第 11.3/10 段:

友谊既不是继承的也不是传递的。 [...]

如果A 类是B 类的friend,而函数f()A 类的friend,则这不会使f() 成为@987654329 类的friend @也一样。

如果您希望它访问Center 的私​​有成员变量,您应该将您的operator &lt;&lt; 声明为Center 类的friend

#ifndef CENTER_H
#define CENTER_H

#include <ostream>

class Center
{
public:
    Center(double x, double y) { xCord = x; yCord = y; }

    friend class Shape;
    friend std::ostream& operator<< (std::ostream& ostr, const Center& c);
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

private:
    double xCord;
    double yCord;
};

#endif

【讨论】:

  • 感谢您的解释。现在很明显,但我忽略了它。
  • @Taylor:不客气。如果此答案解决了您的问题,请考虑接受。
【解决方案2】:

您的运算符

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多