POV-Ray : Newsgroups : povray.off-topic : C++ question : Re: C++ question Server Time
28 Jul 2024 16:15:29 EDT (-0400)
  Re: C++ question  
From: Le Forgeron
Date: 3 Oct 2013 12:22:43
Message: <524d99d3@news.povray.org>
Le 03/10/2013 10:14, Anthony D. Baye nous fit lire :
> I'm working on what is probably a complicated solution to a relatively trivial
> problem.  I have no idea whether I'm doing this right or not (well, obviously,
> I'm doing -something- wrong) but based on everything I've read, and all of the
> examples I could dig up, I don't see anything wrong with my structure.
> 
> basically, I have a custom library:
> 
> #ifndef _MY_LIB_
> #define _MY_LIB_
> #include <iostream>
> #include <cmath>
> using std::ostream;
> 
> namespace geometry {
> 
>     enum pointName{X,Y,Z};
> 
>     class point3d
>     {
>         public:
>         .
>         .
>         .
>         friend ostream &operator <<(ostream &, const point3d &);
> 
>         private:
>     };
> 
>     class vector3d : public point3d
>     {
>         ...
>     };
> 
>     const point3d ORIGIN;
>     const vector3d ZERO_VECTOR;
> }
> 
> class implementations are handled in separate files, and compiled with:
> 
> g++ -g -c -Wall -std=c++0x point3d.cpp vector3d.cpp
> 
> This compiles fine, and everything is awesome until I try to use the << operator
> in my unit test program.  g++ gives me the following:
> 
> g++ -g -Wall -o uTest unit_test.cpp point3d.o vector3d.o
> /tmp/cca86ida.o: In function `point_arithmetic_test()':
> /home/.../Documents/Projects/Planets/unit_test.cpp:56:
> undefined reference to `geometry::operator<<(std::basic_ostream<char,
> std::char_traits<char> >&, geometry::point3d const&)'
> /home/.../Documents/Projects/Planets/unit_test.cpp:57:
> undefined reference to `geometry::operator<<(std::basic_ostream<char,
> std::char_traits<char> >&, geometry::point3d const&)'
> collect2: ld returned 1 exit status
> make: *** [uTest] Error 1
> 
> now unit_test.cpp, like both of my library files uses:
> 
> using namespace geometry;
> 
> if I remove the namespace wrapper from around my classes, everything works.
> 
> can somebody tell me what I'm missing?
> 
you declared a friend function <<, but did you provide its
implementation in some cpp file ? (with accurate namespace matching ?)

reminder: that's a class-free function (not member of point3d), and you
are allowed to implement a function without declaring it first, so it
could happen that your implementation is not matching the signature
declared in the header file without generating an error.

Otherwise, avoid "using std::ostream", and have explicit:
         friend std::ostream &operator <<(std::ostream &, const point3d &);


You might want to replace <iostream> (heavy) with <iosfwd> in the header
files, reserving iostream to the source files that actually need streams
usage.


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.