簡體   English   中英

無效使用不完整類型'class ...' STL 向量

[英]invalid use of incomplete type 'class …' STL vector

我對繼承 STL 向量的 class 的定義有一些疑問。 這個 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

相關代碼在這里列出:

使用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_

向量向量.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文件通常不是正確的方法。 您應該實現 header 文件中的模板。 如果您仍想將實現分開,您可以執行以下操作:

啊:

#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成員來代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM