MSVC++ compiler error C2143

前端 未结 3 763
孤独总比滥情好
孤独总比滥情好 2021-01-25 12:45

The following code excerpt is responsible for a cryptic MSVC++ compiler error:

template class Vec : public vector{
  public:
    Vec() :          


        
相关标签:
3条回答
  • 2021-01-25 13:08

    From MSDN: Compiler Error C2143 (C++)

    An unqualified call is made to a type in the Standard C++ Library:
    // C2143g.cpp
    // compile with: /EHsc /c
    #include <vector>
    static vector<char> bad;   // C2143
    static std::vector<char> good;   // OK
    

    This just bit me. You just have to fix your references to vector<T>, replacing them with std::vector<T>.

    0 讨论(0)
  • 2021-01-25 13:09

    Try

    template<class T> class Vec : public vector<T>{
      public:
        Vec() : vector(){} // no <T>
        Vec(int s) : vector(s){} // same
    
        T& operator[](int i){return at(i);  }
        const T& operator[](int i)const{ return at(i);}
    };
    

    The constructor for a template class does not include the template signature in its name.

    As a side note, your second constructor should really be

    Vec(typename vector<T>::size_type s) : vector(s){} // not necessarily int
    

    Finally, you really shouldn't derive from vector, as it has a non-virtual destructor. Do not attempt to delete a Vec through a pointer to a vector.

    0 讨论(0)
  • 2021-01-25 13:23

    Why are you attempting to inherit from vector? This will cause you a lot of problems. The least of which is that vector does not have a virtual destructor. This will cause the wrong destructor to be called when deleting a polymorphic reference to your class which will lead to memory leaks or general bad behavior.

    For instance, the following code will not call ~Vec() but will call ~vector() instead.

    vector<int> *pVec = new Vec<int>();
    delete pVec;  // Calls ~vector<T>();
    

    The actual compile error you are seeing though is because you're using the template syntax for the base constructor call. Simply remove that and it should compile

    Vec() : vector() {}
    
    0 讨论(0)
提交回复
热议问题