有人介意帮助我解决 C++ 链接/编码难题吗?
我有一个类形状。Shape 需要使用类 Center 的私有数据成员,x 和 y 坐标。我声明朋友类Shape;然后 #include "center.h" 在 Shape.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;
}