朋友功能如何运作

Arteniks

我想学习如何使用朋友功能。第一次尝试时,我没什么问题,也不知道如何解决。我收到以下错误:

|17|error: 'minutes' was not declared in this scope|
|18|error: 'hours' was not declared in this scope|
|24|error: 'minutes' was not declared in this scope|
|24|error: 'minutes' was not declared in this scope|

这是我到目前为止的所有代码:

#include <iostream>
using namespace std;

class Time
{

    int hours;
    int minutes;
    friend Time operator+(const Time & t);
    friend void x(Time h, Time m );

};

Time operator+(const Time & t)
{
    Time sum;
    sum.minutes = minutes + t.minutes;
    sum.hours = hours + t.hours + sum.minutes / 60;
    sum.minutes %= 60;
    return sum;
}


void x(Time h, Time m) {hours = h; minutes = m;}
来自莫斯科的弗拉德

这些错误信息

| 17 |错误:未在此范围内声明“分钟” |

| 18 |错误:未在此范围内声明“小时” |

表示在此功能定义内

Time operator+(const Time & t)
{
    Time sum;
    sum.minutes = minutes + t.minutes;
                  ^^^^^^^
    sum.hours = hours + t.hours + sum.minutes / 60;
                ^^^^^
    sum.minutes %= 60;
    return sum;
}

变量minuteshours并且未声明。该函数不是该类的成员函数。因此,这些变量不是该类对象的数据成员Time它们是未声明的标识符。

Friend函数不会this像非静态成员类函数那样获取隐式参数

这些错误信息

| 24 |错误:未在此范围内声明“分钟” |

| 24 |错误:未在此范围内声明“分钟” |

具有相同的含义。该函数x不是Time类的成员函数。

如果朋友函数operator +使二进制运算符重载,+则它应具有两个参数。

至于第二个朋友函数,那么它的任务似乎是为类型的对象设置值Time

如下面的演示程序所示,应按以下方式声明和定义友元函数。

#include <iostream>
#include <iomanip>

class Time
{
    int hours;
    int minutes;
    friend Time operator +( const Time &t1, const Time &t2 );
    friend void x( Time &t, int h, int m );
    friend std::ostream & operator <<( std::ostream &is, const Time &t );
};

Time operator +( const Time &t1, const Time &t2 )
{
    const int HOURS_IN_DAY = 24;
    const int MINUTES_IN_HOUR = 60;

    Time t;

    t.hours  = t1.hours + t2.hours + ( t1.minutes + t2.minutes ) / MINUTES_IN_HOUR;
    t.hours %= HOURS_IN_DAY;
    t.minutes = ( t1.minutes + t2.minutes ) % MINUTES_IN_HOUR;

    return t;
}

void x( Time &t, int h, int m )
{
    t.hours = h;
    t.minutes = m;
}

std::ostream & operator <<( std::ostream &os, const Time &t )
{
    return 
    os << std::setw( 2 ) << std::setfill( '0' ) << t.hours 
       << ':'
       << std::setw( 2 ) << std::setfill( '0' ) << t.minutes; 
}

int main() 
{
    Time t1;

    x( t1, 16, 10 );

    std::cout << t1 << '\n';

    Time t2;

    x( t2, 10, 20 );

    std::cout << t2 << '\n';

    std::cout << t1 + t2 << '\n';

    return 0;
}

程序输出为

16:10
10:20
02:30

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章