[英]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.