首页 > 解决方案 > 在 C++ 中使用模板的不完整类

问题描述

已解决:请参阅底部的答案

我对 C++ 比较陌生,所以这可能是一个愚蠢的问题,但我正在尝试使用内置的 STL 向量为向量编写一个模板类。这是大学的任务。我创建了一个 Header 文件和一个 cpp-source 文件,所以我可以在 Header 中定义类 Vector 并在源文件中声明它的函数。我收到以下错误:

Vector.cpp:27:59: error: invalid use of incomplete type ‘class Vector<T, n>’
Vector<T, n>& Vector<T, n>::operator=(const Vector<U,n>& v){
                                                           ^
In file included from Vector.cpp:1:0:
Vector.h:5:7: note: declaration of ‘class Vector<T, n>’
 class Vector {
       ^~~~~~
Vector.cpp:42:59: error: invalid use of incomplete type ‘class Vector<T, n>’
 Vector<T, n>& Vector<T, n>::operator+(const Vector<U,n>& v){
                                                           ^
In file included from Vector.cpp:1:0:
Vector.h:5:7: note: declaration of ‘class Vector<T, n>’
 class Vector {
       ^~~~~~

我的代码是这样的:

头文件(Vector.h):

#include <vector>
using namespace std;

template <class T, int n>
class Vector {
public:
    Vector();
    Vector(int);
    Vector(const Vector<T, n>&);

    ~Vector();

    template<class U>
    Vector<T, n> operator=(const Vector<U, n>&);

    T& operator[](int i);

    template<class U>
    Vector<T, n> operator+(const Vector<U, n>&);
    template<class U>
    Vector<T, n> operator-(const Vector<U, n>&);
    template<class U>
    T operator*(const Vector<U, n>&);

    template<class S>
    Vector<T, n> operator*(const S&);

  /*  template<class S>
    friend Vector<T, n> operator*(const S&, Vector<T, n>&);*/

    template<class F>
    Vector<T, n> apply_Funktor();

private:
    vector<T> values;
    const int size;
};
/*
template<class S, class T, int n>
Vector<T, n> operator*(const S& s, const Vector<T, n> v){
    return v * s;
};*/

和源 cpp 文件:

#include "Vector.h"
#include <vector>
using namespace std;

template <class T, int n>
Vector<T, n>::Vector(): size(n){
    vector<T> values;
}

template <class T, int n>
Vector<T, n>::Vector(int v): size(n){
    vector<T> values;
    values.assign(v, n);
}

template <class T, int n>
Vector<T, n>::Vector(const Vector<T, n>& v): size(v.size){
    values = v.values;
}

template <class T, int n>
Vector<T, n>::~Vector(){
    delete values;
}

template<class U, class T, int n>
Vector<T, n>& Vector<T, n>::operator=(const Vector<U,n>& v){
    delete values;
    vector<T> values;
    for(int i = 0; i < size; i++){
        values.push_back((T) v.values[i]);
    }
    return *this;
}

template<class T, int n>
T& Vector<T, n>::operator[](int i){
    return values[i];
}

template<class U, class T, int n>
Vector<T, n>& Vector<T, n>::operator+(const Vector<U,n>& v){
//more Code to come but I already get the error here
}

当我尝试使用 NetBeans 构建我的项目时发生错误。我还没有使用 Vector 的 main。我已经在互联网上搜索了解决方案,但没有找到任何有用的东西。我了解了前向声明,但在我看来这不是这种情况,因为我包括头文件。

谢谢您的帮助 :)

!!!编辑/解决方案:我在课堂上的导师解决了它:问题是,而不是做

template<class U, class T, int n>

我必须这样说:

template<class T, int n>
template<class U>

标签: c++vector

解决方案


推荐阅读