1

誰かがC++のリンク/コーディングの難問で私を助けてくれませんか?

私はクラスShapeを持っています。Shapeは、クラスCenterのプライベートデータメンバーであるx座標とy座標を使用する必要があります。フレンドクラスShapeを宣言します。次に、Shape.hに#include"center.h"を追加します。Shape.cppで、c.xCordを使用するostream&operator <<(ostream&ostr、const Center&c)関数を定義します。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;
}
4

2 に答える 2

4

C ++11規格の11.3/10項によると:

友情は継承も推移的でもありません。[...]

クラスAfriendクラスのBであり、関数f()がクラスのである場合、これはfriendクラスのを作成しAません。f()friendB

次のプライベートメンバー変数にアクセスする場合は、クラスoperator <<として宣言する必要があります。friendCenterCenter

#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
于 2013-02-28T20:03:53.790 に答える
1

演算子<<は、Shapeクラスとは何の関係もありません。友情はオペレーターには及びません。その特定の演算子を友達として宣言する必要があります。

于 2013-02-28T20:08:16.337 に答える