Probleme mit Operatorüberladung
-
Hallo,
ich habe noch nicht soviel Ahnung von c++ und wolle üben Operatoren zu überladen. Dazu wollte ich mir eine Vector Klasse basteln.
Aber schon bei der 1. Überladung von + gibts Probleme:Die Main
#include "Vector3D.h" #include <Windows.h> int main () { Vector3D v = Vector3D(1,1,1); Vector3D z = Vector3D(2,3,4); Vector3D k = z+v; Sleep(20000); return 1; }Vector3D.cpp
#include "Vector3D.h" #include <Iostream> #include <math.h> void Vector3D::sagzahl() {std::cout <<"x= "<< x<<" y= "<<y<<" z= "<<z;} void Vector3D::normalize() {float l = Vector3D::length();l=1/l;x*=l;y*=l;z*=l;} float Vector3D::length() {return sqrt(x*x+y*y+z*z);} float Vector3D::sqrt_length() {return (x*x+y*y+z*z);} Vector3D Vector3D::normale(Vector3D v) {return Vector3D();}Vector3D.h
#pragma once class Vector3D { public: float x,y,z; public: Vector3D(float x_,float y_,float z_): x(x_),y(y_),z(z_){}; Vector3D():x(0),y(0),z(0) {}; ~Vector3D(void){} inline float get_x() {return x;} inline float get_y() {return y;} inline float get_z() {return z;} void normalize(); float length(); float sqrt_length(); Vector3D normale(Vector3D); void sagzahl(); }; Vector3D operator + (const Vector3D& a,const Vector3D& b) {return Vector3D(a.x + b.x, a.y + b.y, a.z + b.z);}Es kommt als Fehler:
Vector3D.obj : error LNK2005: "class Vector3D __cdecl operator+(class Vector3D const &,class Vector3D const &)" (??H@YA?AVVector3D@@ABV0@0@Z) already defined in Main.obj
F:\Vector.exe : fatal error LNK1169: one or more multiply defined symbols foundWas muß ich anders machen?
-
Non-inline Funktionen sollten immer im Header nur deklariert und dann in der cpp definiert werden (nicht sicher ob es jetzt das Problem ist, aber ich könnts mir vorstellen)
-
1. Deklaration des op+ nach Vector3D.h
2. Implementation nach Vector3D.cpp (nicht wie jetzt in .h!)d.h. ähnlich, wie du das mit normalize() und length()
auch gemacht hast.Vector3D.cpp und Main.cpp lesen beide Vector3D.h, daher der Fehler
-
helpie schrieb:
1. Deklaration des op+ nach Vector3D.h
2. Implementation nach Vector3D.cpp (nicht wie jetzt in .h!)d.h. ähnlich, wie du das mit normalize() und length()
auch gemacht hast.Vector3D.cpp und Main.cpp lesen beide Vector3D.h, daher der Fehler
Danke, klappt jetzt
-
oder die Funktion (bzw. den Operator) als inline deklarieren...