相关疑难解决方法(0)

重载friend operator <<为模板类

我正在尝试重载运算符<<作为模板类对的朋友,但我不断收到编译器警告说

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)

c++ operators

28
推荐指数
2
解决办法
3万
查看次数

在C++中重载提取运算符>>

可能重复:
运算符重载

我必须编写一个时钟程序,在这个程序中我可以输入小时,分钟和秒,同时重载提取操作符.这些是我的代码:

clockType.h

#include<iostream>
using namespace std;

class clockType
{
public:
   clockType();
   void getTime();
   friend istream& operator>>(istream&, const clockType);
private:
   int hr, min, sec;
}
Run Code Online (Sandbox Code Playgroud)

clockType.cpp

#include<iostream>
#include'clockType.h"
using namespace std;

clockType::clockType()
{
    hr = 0;
    min = 0;
    sec = 0;
}

void clockType::getTime()
{
    while(hr>=24)
        hr = hr - 24;
    while(min>=60)
        min = min - 60;
    while(sec>=60)
        sec = sec - 60;
    cout<<setfill('0')
        <<setw(2)<<hr<<":"
        <<setw(2)<<min<<":"
        <<setw(2)<<sec<<endl;
 }

 istream& operator>>(istream& in, clockType cl)
 {
    in>>cl.hr>>cl.min>>cl.sec;
    return in;
 } …
Run Code Online (Sandbox Code Playgroud)

c++ visual-c++

3
推荐指数
1
解决办法
4705
查看次数

标签 统计

c++ ×2

operators ×1

visual-c++ ×1