oop - errors when compiling class in c++ -


i tried create class 3-d vector in c++, there errors. have learnt little bit of oop in python before, i'm still pretty new oop , c++. created header file threevector.h, file class threevector.cpp , main program file main.cpp. want know have done wrong.

// threevector.h #ifndef threevector_h #define threevector_h #include <iostream>  class threevector {     private:         double xcoord, ycoord, zcoord;      public:         threevector();         threevector(double x, double y, double z, char type);         void print ();       }; #endif // threevector_h   //threevector.cpp #include "threevector.h" #include <cmath>  threevector() {     xcoord = 0.0;     ycoord = 0.0;     zcoord = 0.0; }  threevector(double x, double y, double z, char type) {     if (type == 'c') {         // cartesian coordinate         xcoord = x;         ycoord = y;         zcoord = z;     }      else if (type == 'p') {         // polar coordinate         // x = r, y = phi, z = theta         xcoord = x*sin(y)*cos(z);         ycoord = x*sin(y)*sin(z);         zcoord = x*cos(y);         } }  void print () {     std::cout << xcoord << '\t' << ycoord << '\t' << zcoord << std::endl; }   // main.cpp #include "threevector.h" #include <cmath> #include <iostream>  using namespace std;  int main() {     threevector v0;     v0.print();      threevector v1(-1,2,4.384,'c');     cout << "v1 = ";     v1.print();      return 0; } 

the following error messages get:

main.cpp(.text+0x15): undefined reference 'threevector::threevector()' main.cpp(.text+0x15): undefined reference 'threevector::print()' main.cpp(.text+0x15): undefined reference 'threevector::threevector::threevector(double, double, double, char)' main.cpp(.text+0x15): undefined reference 'threevector::print()' [error] ld returned 1 exit status 

you defined threevector's methods wrong. should be:

threevector::threevector() {     xcoord = 0.0;     ycoord = 0.0;     zcoord = 0.0; }  threevector::threevector(double x, double y, double z, char type) {     if (type == 'c') {         // cartesian coordinate         xcoord = x;         ycoord = y;         zcoord = z;     }      else if (type == 'p') {         // polar coordinate         // x = r, y = phi, z = theta         xcoord = x*sin(y)*cos(z);         ycoord = x*sin(y)*sin(z);         zcoord = x*cos(y);         } }  void threevector::print () {     std::cout << xcoord << '\t' << ycoord << '\t' << zcoord << std::endl; } 

all threevector's methods in threevector's scope.

don't forget compile same main.cpp:

g++ threevector.cpp main.cpp 

this linked threevector in same object file.


Comments