开发者

why compiler gives undefined reference

I have this code:

in header file

     class开发者_如何学Go SocialNet {
         private:
               // some data 
         public:
               // some other operations

          template <typename T, typename V> 
            T find(V identifier, const vector<T>& objects) const;   
      };

in .cpp file

  // in that file, I haven't use that function
  // I have four other template functions used in that header, and compiler have 
  //not   give any error 
    template <typename T, typename V> 
    T find(V identifier, const vector<T>& objects) const {

         // some things to do required job
     }

in main.cpp

// I have used that function, for the first time in that file

When I compile, I have below error;

/main.cpp .. undefined reference to SocialNet :: find ( ....  ) ...

Why?

With explanation, please, inform me about what the undefined reference means


You can not implement a template in a .cpp file, the function definition of find should be there in the header file. See this FAQ Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file? for more details.


You forgot to write SocialNet:: when defining find

template <typename T, typename V> 
T SocialNet::find(V identifier, const vector<T>& objects) const {
//^^^^^^^^^^^ note this!

 }

SocialNet:: tells the compiler that the function find is a member function of class SocialNet. In the absence of SocialNet::, the compiler will treat find as free function!


You did not scope your function. That is, you did not preface it with your class name and scope operator (in this case SocialNet::).

When implementing functions outside of the class itself, you must scope the function in order to make it work properly so the compiler knows which function it is compiling (i.e. two classes can have two different functions with the same name).

The undefined reference error comes particularly from the compiler when you have declared a function in a class, but have not implemented it (you need {} braces to implement a void function which does nothing; a semi-colon after the signature is purely a declaration)

Regards,
Dennis M.


You are missing the class name before T find(...) definition.

template <typename T, typename V> 
T SocialNet :: find(V identifier, const vector<T>& objects) const {

     // some things to do required job
}  

You need to place SocialNet before find(...) because find(...) is declared in scope of class SocialNet. Since defining the functionality outside the scope of the class declaration, it needs to be explicitly mentioned that the method being defined belongs to class SoicalNet. Note that :: is the scope resolution operator. Also, you need to include the header in the source file SocialNet.cpp.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜