【问题标题】:invalid use of incomplete type 'class ...' STL vector不完整类型'class ...' STL向量的无效使用
【发布时间】:2020-07-21 04:19:00
【问题描述】:

我对继承 STL 向量的类的定义有一些疑问。此类应公开继承自 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

这里列出了相关代码:

使用MVector.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) {

}

【问题讨论】:

    标签: c++ vector compiler-errors stl stdvector


    【解决方案1】:
    template<class T2, class T, int size>
    MVector<T,size> MVector<T,size>::operator+(const MVector<T2,size>& y)
    

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

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

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

    啊:

    #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(和大多数其他标准库类)派生很少合适,您应该有一个std::vector 成员。

    【讨论】:

    • 感谢您的回答。您是否有理由不从 STL 类派生或只是约定?
    • 他们没有虚拟析构函数,所以这样做并不完全安全,请参阅stackoverflow.com/questions/1073958/…
    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2011-10-22
    相关资源
    最近更新 更多