以下代码在 Visual Studio 2015 中编译没有问题,但使用 minGW 时会收到下面显示的警告和错误:
#include <iostream>
using std::ostream;
template<typename ElemType, int SIZE>
class Array
{
friend ostream &operator<<(ostream &out, const Array<ElemType, SIZE> &value);
ElemType operator[](int index) const;
private:
ElemType elements[SIZE];
};
template<typename ElemType, int SIZE>
ostream &operator<<(ostream &out, const Array<ElemType, SIZE> &value);
template<typename ElemType, int SIZE>
ostream &operator<<(ostream &out, const Array<ElemType, SIZE> &value)
{
out << elements[0];
return out;
}
mingw32-g++.exe -Wall -g -pedantic-errors -pedantic -Wextra -Wall -std=c++98 -c Test.cpp
Test.cpp:7:79: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Array<ElemType, SIZE>&)' declares a non-template function [-Wnon-template-friend]
Test.cpp:7:79: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
Test.cpp: In function 'std::ostream& operator<<(std::ostream&, const Array<ElemType, SIZE>&)':
Test.cpp:21:11: error: 'elements' was not declared in this scope
我远不是这方面的专家,所以我不确定问题是什么。似乎它告诉我它需要在类本身的朋友声明之前的以下代码,但是当我把它放在那里时,它会导致其他编译错误:
template<typename ElemType, int SIZE>
提前致谢!
在进行@Trevor Hickey 在他的帖子中建议的更改之后,关于朋友模板功能的警告消失了。但是,我仍然收到有关“元素”(在友元函数中)未在范围内声明的错误。