undefined reference to operator<<

前端 未结 2 777
梦毁少年i
梦毁少年i 2021-01-04 10:28

I have a regular class (not a template, that is) with a private friend operator<<

it\'s declaration is:

std::ostream& operator<<(std:         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 11:17

    David gave a very good answer to the question. Here I am just providing an example for easy understanding.

    in my header file:

    namespace BamTools {
    class SomeBamClass {
    .....
    public:
        friend std::ostream& operator<<(std::ostream& ous, const SomeBamClass& ba);
        .....
    }
    }
    

    In the cpp file:

    using namespace BamTools; // this work for Class member function but not friends
    using namespace std;
    
    ........
    std::ostream& operator<<(std::ostream &ous, const SomeBamClass &ba) {
      // actual implementation
      return ous;
    }
    

    The above will give you undefined reference to operator<<(.., const SomeBamClass&) when you try to link to this library from your own applications because it is declaration and implementation of an operator outside the namespace.

    undefined reference to `BamTools::operator<<(std::ostream&, BamTools::SomeBamClass const&)'
    

    The only thing works for me is to add namespace inclosure to the friend function in the implementation file:

    namespace BamTools {
    std::ostream& operator<<(std::ostream &ous, const SomeBamClass &ba) {
    ...
       return ous;
    }
    }
    

    using ... BamTools::operator<<(..., const BamTools::SomeBamClass&) will result in a compiler error for my g++ 5.4.0.

提交回复
热议问题