无效使用不完整类型 'class ...' STL 向量

invalid use of incomplete type 'class ...' STL vector

我对 class 继承 STL 向量的定义有一些疑问。 class 支持从 std::vector 公开继承,但我不断从编译器那里收到以下错误。我几乎可以肯定这是由于错误包含 <vector>,但我不知道如何修复它。

In file included from useMVector.cpp
[Error] invalid use of incomplete type 'class MVector<T, size>'
In file included from MVector.cpp
     from useMVector.cpp
[Error] declaration of 'class MVector<T, size>'
recipe for target 'useMVector.o' failed

此处列出相关代码:

useMVector.cpp:

#include <stdlib.h>
#include "MVector.cpp"

using namespace std;

int main() {
    return 0;
}

MVector.h:

#ifndef _MVECTOR_
#define _MVECTOR_

#include <iostream>
#include <stdlib.h>
#include <vector>

using namespace std;

template<class T, int size>
class MVector : public std::vector<T> {
    public:
        // constructer:
        MVector();
        // operator=, copy constructor and destructor from std::vector
        // iterator from std::vector

        // methodes:

        // addition with vector
        template<class T2>
        MVector<T, size> operator+(const MVector<T2,size>& y);

       ...
};

#endif // _MVECTOR_

MVector.cpp

#include "MVector.h"

template<class T, int size>
MVector<T, size>::MVector() : std::vector<T>::vector(size, 0) {};

template<class T2, class T, int size>
MVector<T,size> MVector<T,size>::operator+(const MVector<T2,size>& y) {

}
template<class T2, class T, int size>
MVector<T,size> MVector<T,size>::operator+(const MVector<T2,size>& y)

不正确,您实际上需要声明两个单独的模板,一个用于 class,一个用于方法:

template<class T, int size>
template<class T2>
MVector<T,size> MVector<T,size>::operator+(const MVector<T2,size>& y) {

}

请注意,包含 .cpp 文件通常不是正确的方法。您应该在头文件中实现模板。如果您仍想将实现分开,您可以这样做:

A.h:

#pragma once

template<typename T>
class A
{
  A();
};

#include "A_impl.h"

A_impl.h:

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

您可以根据自己的习惯命名 A_impl.h,一些代码库使用类似 A.ipp.

的名称

派生自 std::vector(以及大多数其他标准库 classes)很少是合适的,您应该有一个 std::vector 成员。