c++ - 在 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>
解决方案
推荐阅读
- javascript - 我在 mvc Web 应用程序上的提交按钮有问题
- css - 创建扩展 Tailwind css 类的类
- highcharts - Highcharts:同一窗格中具有不同 Y 轴的多个图表?
- c# - 如何使用键中的点添加到路由值元素
- javascript - 单击链接时,React 使用 ref 滚动到特定组件
- pandas - 熊猫中两个数据框的瀑布图
- c++ - 在左下角 Windows 凭据提供程序中显示用户列表
- java - 如何使用 Java 8 使用 A 的构造函数将对象 A 的数组转换为对象 B 的数组?
- c++ - 我无法下载 minGW 包
- discord - 如何检查我的不和谐机器人是否已经对一个人进行了 dm 并且它不会再次对该人进行 dm (discord.py)