首页 文章

无法访问朋友类的私人会员

提问于
浏览
1

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

我有一个类Shape . Shape需要使用类Center的私有数据成员,x和y坐标 . 我宣布朋友类Shape;然后在Shape.h中#include“center.h” . 在Shape.cpp中,我定义了我的ostream&operator <<(ostream&ostr,const Center&c)函数,它使用c.xCord; c.yCord访问中心的私人数据成员 .

当我尝试编译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;
}

2 回答

  • 4

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

    友谊既不是遗传也不是传递 . [...]

    如果类 A 是类 Bfriend ,并且函数 f() 是类 Afriend ,则这也不会使 f() friendB .

    如果您希望它访问 Center 的私有成员变量,则应将 operator << 声明为 CenterCenter

    #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
    
  • 1

    您的运算符<<与类Shape无关 . 友谊不会扩展到运营商 . 您需要将该特定运算符声明为朋友 .

相关问题