Home C++ How to define an operator that is inside a nested class
Reply: 2

C++ How to define an operator that is inside a nested class

NoobProgrammer Published in 2018-02-13 03:51:59Z

I am having trouble with defining an operator that is within a nested class that is also templated. I understand how to declare and define it within the .h file, but I want to declare it in the .h file and define it in a .hpp file. For example:


template <typename T>
class List {
    class const_iterator {   //nested class
        const T & operator*() const;

Now here is the part I don't quite understand:


#include "List.h"
template <typename T>
typename List <T>::const_iterator & List <T>:: operator*() const //error line
    //do stuff

The error I am receiving on line 4 of the Line.hpp is:

Out-of-line definition of 'operator*' does not match any declaration in 'List<T>'

I am looking for a solution that involves solely fixing the .hpp file.

Miles Budnek
Miles Budnek Reply to 2018-02-13 04:08:30Z

As the error says, your definition doesn't match your declaration. You've declared a member operator* of the class List<T>::const_iterator that returns a const T&, but your definition is for the member operator* of the class List<T> that returns a List<T>::const_iterator&.

Definitions of member functions of class templates, nested or not, follow the same pattern as any other function: ReturnType FunctionName(ParameterList)

The appropriate definition for that declaration is:

  template <typename T>
  const T& List<T>::const_iterator::operator*( ) const
//^^^^^^^^                                    ^
// |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
// Return type        |                       (empty) parameter list
//                    Function name
Remy Lebeau
Remy Lebeau Reply to 2018-02-13 04:09:30Z

Your .hpp is trying to define an operator* that is a member of List<T> and returns a reference to a List<T>::const_iterator. That is not what your .h declares. It declares an operator* that is a member of List<T>::const_iterator and returns a reference to a T.

Try this instead:

#include "List.h"

template <typename T>
const T& List<T>::const_iterator::operator*() const
    //do stuff
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.298982 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO