简体   繁体   中英

Error C++ : ‘const_iterator’ does not name a type;

I have a class called Nuage (which is a collection of Points) where I will use the functions of the class Vector to manipulate the class. The nuage.cpp file is:

#include <iostream>
#include "nuage.hpp"


template <typename T>
Nuage<T>::Nuage(){}

template <typename T>
void Nuage<T>::ajouter(const T& p) {
    v.push_back(p);
}

template <typename T>
unsigned int Nuage<T>::size() const {
    return v.size();
}


template <typename T>
const_iterator Nuage<T>::begin() const{
    return v.begin();


template <typename T>
Nuage<T>::~Nuage(){}

nuage.hpp is:

#ifndef NUAGE_HPP
#define NUAGE_HPP
#include <cstdlib>
#include <sstream>
#include <vector>

template <typename T>    
class Nuage {

    private:
        std::vector<T> v;
    
    public:
        using const_iterator = typename std::vector<T>::const_iterator;
        Nuage();
        void ajouter(const T&);
        unsigned int size() const;
        const_iterator begin() const;
        ~Nuage();
};

#endif

I have an error that says:

error: ‘const_iterator’ does not name a type; did you mean ‘constexpr’?

The error is in this line: const_iterator Nuage<T>::begin() const{

Can someone help me to find it? THanks

Use

template <typename T>
typename Nuage<T>::const_iterator Nuage<T>::begin() const{
    return v.begin();
}

When the compiler works with your .cpp file you reference a type const_iterator which does not exist. Only Nuage<T>::const_iterator exists. Easy to oversee.

The typename keyword is needed beacuse Nuage<T>::const_iterator is a dependent name. The compiler needs to be told that this expression is a type, not a static variable or a function or something else inside the class.

const_iterator exists only within the scope of instantiation of Nuage for some T. You have two options to fix your code. Either add explicit Nuage<T>:: :

template <typename T>
typename Nuage<T>::const_iterator Nuage<T>::begin() const{
    return v.begin();
}

or use postfix return type notation :

template <typename T>
auto Nuage<T>::begin() -> const_iterator const{
    return v.begin();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM