【发布时间】:2011-04-12 02:42:06
【问题描述】:
我的项目中出现了一个神秘错误:
预期的构造函数、析构函数或类型转换
它不允许我使用我重载的operator<<。在我将我的课程 (myVector) 变成 template 之前,这以前有效。
//MyVector class
//An implementation of a vector of integers.
template <class T>
class MyVector{
public:
//Purpose: Initialize an object of type MyVector
//Parameters: none.
//Returns: nothing.
MyVector();
//------------------------------------------------
//Purpose: Initialize an object of type MyVector
//Parameters: an integer.
//Returns: nothing.
//------------------------------------------------
MyVector(int);
//Purpose: Destroys objects of type MyVector
//Parameters: none.
//Returns: nothing
//------------------------------------------------
~MyVector();
//Purpose: Returns the current size of the MyVector.
//Parameters: none.
//Returns: the size.
int size() const;
//------------------------------------------------
//Purpose: Returns the capacity of the MyVector.
//Parameters: none.
//Returns: int.
int capacity() const;
//------------------------------------------------
//Purpose: Removes the entries of MyVector.
//Parameters: none.
//Returns: nothing.
void clear();
//------------------------------------------------
//Purpose: Appends a given integer to the vector.
//Parameters: an integer.
//Returns: nothing.
void push_back(T);
//------------------------------------------------
//Purpose: Shows what's at a given position.
//Parameters: an integer index.
//Returns: an integer.
T at(int) const;
MyVector(const MyVector& b);
const MyVector& operator=(const MyVector&);
//------------------------------------------------
private:
int _size;
int _capacity;
int* head;
//Purpose: Increases the capacity of a MyVector when it's
// capacity is equal to it's size. Called by push_back(int)
//Parameters/Returns: nothing.
void increase();
//Purpose: Copies the given vector reference.
//Param: MyVector reference.
//Returns: nothing.
void copy(const MyVector&);
//Purpose: Frees MyVector up for an assignment.
void free();
};
template <class T>
ostream& operator<<(ostream&, const MyVector<T>);
//This line is giving me the error.
#endif
我在一个单独的文件中有操作员的代码:
template <class T>
ostream& operator<<(ostream& os, const MyVector<T> V){
int N = V.size();
os << endl;
for(int i = 0; i<N; i++){
os << V.at(i)<<endl;
}
return os;
}
我查看了其他问题,但似乎没有一个与我的匹配。帮助将不胜感激。谢谢!
【问题讨论】:
-
你在某处有
using std::ostream;或using namespace std;(恶心)吗?如果没有,编译器就不会知道ostream是什么。 -
有人可以压缩一下上面代码的格式吗?
-
解释你在哪里定义了模板类。在同一个文件或不同的文件中。
-
评论应该告诉我们什么是不明显的。您不需要我们告诉默认 ctor 的用途是什么,或者它的参数,或者它的返回值。
increase的目的评论很好。最糟糕的是,当您将其制作为模板但忘记更新 cmets 时,所有 cmets 都已过时;这些现在很混乱,
标签: c++ templates compiler-errors