c++ class



  • Hallo,

    ich mochte gerne ein class Definiren, indem ich euklidische Abstand berechne. Ich bekomme Fehlermeldungen:

    binary 'operator -' has too many parameters,
    'CPoint' does not define this operator or a conversion to a type acceptable to the predefined operator,
    left of '.length' must have class/struct/union

    Hier mein C++ Code:

    class CPoint
    {
    public:
    float x, y;
    CPoint(float _x, float _y)
    : x(_x), y(_y) {;}

    void set(float _x, float _y) { x = _x; y = _y; }
    float diff(CPoint p1, CPoint p2)
    {
    return (p2 - p1).length();
    }
    CPoint operator -(CPoint p1, CPoint p2)
    {
    return CPoint(p1.x - p2.x, p1.y - p2.y);
    }
    float length()
    {
    return sqrt(x*x+y*y);
    }
    };

    Hoffentlich habe ich mein Problem veständlich beschrieben.
    Danke



  • Zieh mal diff() und operator-() aus der Klasse raus



  • ns schrieb:

    ...

    1. Beim nächsten mal setze bitte den Code in die C/C++-Tags
    2. Ich würde häufiger mit Referenzübergaben arbeiten, du kopierst hier extrem häufig deine Klasse.
    3. Ein paar Umbrüche würden IMHO die Lesbarkeit erhöhen.
    4. Wenn man den operator- überläd sollte man auch operator-= überladen. Und ersteren über zweiten außerhalb der Klasse implementieren.

    Edit: folgendes habe ich unter VC2008 getestet:

    #include <cmath>
    
    class CPoint
    {
      public:
        float x;
        float y;
    
        CPoint(float x, float y)
        :   x(x),
            y(y)
        {}
    
        void set(float x, float y)
        {
            this->x = x;
            this->y = y;
        }
    
        CPoint& operator -=(CPoint const & p)
        {
            this->x -= p.x;
            this->y -= p.y;
            return *this;
        }
    
        float length() const
        {
            return std::sqrt(x*x + y*y);
        }
    };
    
    CPoint operator-(CPoint const & p1, CPoint const & p2)
    {
        CPoint p(p1);
        p -= p2;
        return p;
    } 
    
    float diff(CPoint const & p1, CPoint const & p2)
    {
        return (p1 - p2).length();
    }
    


  • Ich danke euch für die Hilfe!

    Es kommen leider noch fehler raus:

    'const CPoint' does not define this operator or a conversion to a type acceptable to the predefined operator

    left of '.length' must have class/struct/union Build log was saved at "file://f:\EA\Debug\BuildLog.htm"

    Gruß ns



  • ns schrieb:

    Ich danke euch für die Hilfe!

    Es kommen leider noch fehler raus:

    Ich habe meinen Code mal leicht überarbeitet, und unter VC2008 getestet (s.o.)



  • ich arbeite unter VS2005, konnte daran liegen?



  • danke euch!

    asc, dein Code funktioniert einwandfrei. Hab meine main.cpp Datei korrigiert.
    Danke.


Anmelden zum Antworten