gpt4 book ai didi

c++ - 无法访问好友类的私有(private)成员

转载 作者:行者123 更新时间:2023-11-30 01:23:20 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

Friendship is neither inherited nor transitive. [...]

如果类AfriendB和函数 f()friendA , 这不会使 f()一个friendB

您应该声明您的 operator <<作为friendCenter如果你想让它访问 Center 的私有(private)成员变量:

#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

关于c++ - 无法访问好友类的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15144573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com