我必须为类分配实现一个名为Stack
的模板类。 Stack有一个重载的流插入操作符。
以下是Stack.h文件的相关摘录:
...
#include <iostream>
using namespace std;
template<class T>
ostream& operator<<(ostream&,Stack<T>&);
template<class T>
class Stack
{
public:
friend ostream& operator<< <T>(ostream&,Stack<T>&);
...
};
#include "Stack.cpp"
...
我无法更改Stack.h,因为它是按原样给出的。 Stack.cpp的相关摘录是:
template <class T>
ostream& operator<< (ostream& out, Stack<T>& stack)
{
Stack<T>::Node* current = stack.top;
out << "[";
while (current)
{
out << current->element;
current = current->next;
if (current)
out << ",";
}
out << "]";
return out;
}
...
这在Visual Studio中编译并正常工作,但是,当使用g ++编译时,它会出现以下错误:
Stack.cpp:4: syntax error before '&'
Stack.cpp:4: 'ostream' was not declared in this scope
Stack.cpp:4: 'out' was not declare din this scope
Stack.cpp:4: 'Stack' was not declared in this scope
Stack.cpp:4: 'T' was not declared in this scope
Stack.cpp:4: 'stack' was not declared in this scope
Stack.cpp:5: declaration of 'operator <<' as non-function
这是为什么?可以做些什么来解决它?
编辑:我补充说我已经包含了iostream并提供了命名空间。
答案 0 :(得分:2)
您无法在Stack<T>
声明中引用未声明的operator<<
。您需要在Stack.h的顶部或在包含Stack.h的每个文件中包含Stack.h之前的前向声明template<class T> Stack;
。
答案 1 :(得分:2)
您应该让您的教授允许对头文件进行一些更改,如下所示:
#include <iostream>
//using namespace std; is a VERY bad idea in header files, since it infects the entire program
template<class T>
class Stack; // Casey's fix
// need to qualify ostream since using namespace std; went away
template<class T>
std::ostream& operator<<(std::ostream&,Stack<T>&);
template<class T>
class Stack
{
public:
friend std::ostream& operator<< <T>(std::ostream&,Stack<T>&);
...
};
// The .cpp extension by convention is used only for source files, not for inclusion targets.
// Pick a different extension for template implementations, which get passed to #include
#include "Stack.impl"
如果你的教授没有看到这些变化的价值,那么由于你将要学习的所有坏习惯,留在他的班级将是非常消极的,你应该开始考虑学习C ++的其他选择。
答案 2 :(得分:0)
问题是我试图分别编译Stack.cpp。解决方案是,仅编译使用模板类的文件,在本例中为main.cpp
我错误的makefile看起来如下:
main: main.o Stack.o
g++ -static main.o Stack.o -o main
main.o: main.cpp
g++ -c main.cpp
Stack.o: Stack.cpp Stack.h
g++ -c Stack.cpp
正确的makefile是
main: main.o
g++ -static main.o -o main
main.o: main.cpp Stack.cpp Stack.h
g++ -c main.cpp
感谢juanchopanza指出这一点。