Nicht zugreifen friend class private Mitglieder
Würde jemand Verstand hilft mir mit einem C++ - Verknüpfung/Programmierung Rätsel?
Habe ich eine Klasse Form. Form verwenden muss, die Klasse Center die privaten Daten der Mitglieder, die x-und y-Koordinaten. Ich erkläre Freund Klasse Form; und dann #include "center.h" in der Form.h. In Shape.cpp definiere ich meine ostream& operator<< (ostream& ostr, const Center& c) - Funktion, die c verwendet.xCord; c.yCord zugreifen Center die privaten Daten der Mitglieder.
Wenn ich versuche zu kompilieren Shape.cpp ich bekomme Zugriff Fehler für diejenigen Daten, Variablen, die wie ich noch nicht erklärte Form, wie ein Freund der Klasse. Ich habe das Gefühl, das hat etwas zu tun mit der Verknüpfung, um zur compile-Zeit. Wie kann ich dieses Problem beheben?
#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<<(ostream&,const Center&)
ein Freund von Shape
?Guter Punkt. Ich habe es verschoben in der Mitte der Klasse. Vielen Dank für den Hinweis.
InformationsquelleAutor Taylor | 2013-02-28
Du musst angemeldet sein, um einen Kommentar abzugeben.
Pro Absatz 11.3/10 der C++11 Standard:
Wenn die Klasse
A
ist einfriend
KlasseB
und Funktionf()
ist einfriend
KlasseA
dies nicht machenf()
einefriend
KlasseB
als gut.Sollten Sie erklären Ihre
operator <<
alsfriend
KlasseCenter
wenn Sie es wollen, um Zugriff auf private member-Variablen derCenter
:Du bist herzlich willkommen. Wenn diese Antwort Ihr problem löst, überlegen Sie sich bitte, es anzunehmen.
InformationsquelleAutor Andy Prowl
Ihre operator << hat nichts zu tun mit der Klasse Form. Die Freundschaft erstreckt sich nicht auf den Betreiber. Sie müssen erklären, dass bestimmte Netzbetreiber als Freund.
InformationsquelleAutor Ryan Witmer