Inherited from std :: vector, compiler error? (the most unpleasant parsing)

For people who see this question: Take a look at the answer and think about using: cdecl

Why the code below gives a compiler error:

prog.cpp: In function ‘int main()’:
prog.cpp:23:4: error: request for member ‘size’ in ‘a’, which is of non-class typeRangeVec<int>(RangeVec<int>)’
  a.size();
    ^

I don’t understand what happened with this code?

#include <iostream>
#include <vector>

template<typename Type>
class RangeVec: public std::vector<Type> {
    public:

        RangeVec( const RangeVec & v): std::vector<Type>(v){}
        RangeVec( const RangeVec && v): std::vector<Type>(std::move(v)) {}

        RangeVec( const std::vector<Type> &v)
            : std::vector<Type>(v)
        {
            //std::sort(std::vector<Type>::begin(),std::vector<Type>::end());
        }
};

int main(){
    std::vector<int> v;
    RangeVec<int> b(v);
    RangeVec<int> a(  RangeVec<int>(b) );
    a.size(); // b.size() works ???? why??
}
+4
source share
1 answer
 RangeVec<int> a(  RangeVec<int>(b) );

This is a function declaration athat returns RangeVec<int>and accepts one argument called a btype RangeVec<int>. This is the most unpleasant parsing . You can fix it using C ++ 11 syntax syntax:

 RangeVec<int> a{RangeVec<int>{b}};

Or, if you don't have a C ++ 11 compiler, just enter an extra pair of brackets:

 RangeVec<int> a((RangeVec<int>(b)))

, .

+6

Source: https://habr.com/ru/post/1546039/


All Articles