我正在尝试重载运算符<<作为模板类对的朋友,但我不断收到编译器警告说
friend declaration std::ostream& operator<<(ostream& out, Pair<T,U>& v) declares a non template function
Run Code Online (Sandbox Code Playgroud)
对于此代码:
friend ostream& operator<<(ostream&, Pair<T,U>&);
Run Code Online (Sandbox Code Playgroud)
作为推荐说,它给出了第二个警告
if this is not what you intended, make sure the function template has already been declared and add <> after the function name here
Run Code Online (Sandbox Code Playgroud)
这是函数定义
template <class T, class U>
ostream& operator<<(ostream& out, Pair<T,U>& v)
{
out << v.val1 << " " << v.val2;
}
Run Code Online (Sandbox Code Playgroud)
这是整个班级.
template <class T, class U>
class Pair{
public:
Pair(T v1, U v2) : val1(v1), val2(v2){} …Run Code Online (Sandbox Code Playgroud) 有这样的代码.
const std::string DeviceTypeStrings[] ={ "A", "B", "C", "D", "E" };
enum DeviceTypes { A = 0, B, C, D, E };
template <DeviceTypes T> class DeviceType;
template <DeviceTypes T> std::ostream& operator<< (std::ostream& output, const DeviceType<T>& dev);
template <DeviceTypes T> class DeviceType {
public:
static const int value = T;
static const std::string string;
friend std::ostream & operator<< <>(std::ostream & output, const DeviceType<T> & deviceType );
};
template <DeviceTypes T> const std::string DeviceType<T>::string = DeviceTypeStrings[T];
template <DeviceTypes T> std::ostream & …Run Code Online (Sandbox Code Playgroud) 我正在尝试重载林类中的+运算符,林是树的集合,而+运算符应该将两个林合并为一个.我有以下代码作为我的类定义:
template<typename NODETYPE>
class Forest
{
public:
friend Forest& operator+<>(Forest&, Forest&);
friend ostream& operator<<<>(ostream&, const Forest&);
friend istream& operator>><>(istream&, Forest&);
Forest();
Forest( const Forest& otherForest);
~Forest();
void nodes(int&) const;
private:
ForestNode<NODETYPE> *root;
ForestNode<NODETYPE> *getNewNode( const NODETYPE &);
};
Run Code Online (Sandbox Code Playgroud)
以下是我对operator +的实现:
template<typename NODETYPE>
Forest& operator+<>(Forest& f1, Forest& f2)
{
f3 = new Forest();
f3.root = *f1.*root;
f3.root.sibling = *f2.*root;
*f1.root = 0;
*f2.root = 0;
return f3;
}
Run Code Online (Sandbox Code Playgroud)
我在编译时遇到以下错误:
|28|error: expected constructor, destructor, or type conversion before '&' token|
第28行指的是我的运算符+实现的签名.
我认为要纠正它我应该添加到返回类型,给出: …