Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Для новичков > дружественные функции


Автор: pycha 10.7.2008, 20:09
Драсте. У меня тут возникли непонятки с созданием дружественной функции. Вот есть клас:
Код

#ifndef _M_H_
#define _M_H_
#include <iostream>
using namespace std;
class Time
{
private:
    int hours;
    int minutes;
public:
    Time();
    Time(int h, int m=0);
    void addmin(int m);
    void addhr(int h);
    void reset(int h=0, int m =0);
    Time::Time operator+ (const Time & t) const;
    Time::Time operator- ( const Time & t) const;
    Time::Time operator* (double n) const;
    friend Time operator* (double m, const Time & t)
    {    return t*m;}
    friend ostream & operator<<(ostream & os, const Time & t);
};
#endif


Мне нужно перегруженые операторы реализовать в виде дружественных функций. Исходя с того что я знаю я написал вот так:

Код

#ifndef _M_H_
#define _M_H_
#include <iostream>
using namespace std;
class Time
{
private:
    int hours;
    int minutes;
public:
    Time();
    Time(int h, int m=0);
    void addmin(int m);
    void addhr(int h);
    void reset(int h=0, int m =0);
    friend Time operator+ (const Time & g, const Time & t) const;
    friend Time operator- (const Time & g, const Time & t) const;
    friend Time operator* (const Time & g, double n) const;
    friend Time operator* (double m, const Time & t)
    {    return t*m;}
    friend ostream & operator<<(ostream & os, const Time & t);
};
#endif


Вот сами функции:

Код

#include "m.h"
Time::Time()
{
    hours = minutes=0;
}
Time::Time(int h, int m)
{
    hours = h;
    minutes = m;
}
void Time::addmin(int m)
{
    minutes +=m;
    hours += minutes/60;
    minutes %=60;
}
void Time::addhr(int h)
{
    hours +=h;
}
void Time::reset(int h, int m)
{
    hours = h;
    minutes=m;
}
Time operator+(const Time&g,const Time&t)const
{
    Time sum;
    sum.minutes = g.minutes + t.minutes;
    sum.hours= g.hours+t.hours+sum.minutes/60;
    sum.minutes %= 60;
    return sum;
}
Time operator-(const Time & g ,const Time & t) const
{
    Time diff;
    int tot1, tot2;
    tot1= t.minutes + 60 * t.hours;
    tot2=g.minutes + 60 * g.hours;
    diff.minutes= (tot2 - tot1)%60;
    diff.hours = (tot2- tot1)/60;
    return diff;
}
Time operator *(const Time & g, double mult) const
{
    Time result;
    long totalminutes = g.hours * mult * 60 + g.minutes * mult;
    result.hours = totalminutes / 60;
    result.minutes = totalminutes%60;
    return result;
}
ostream & operator <<(ostream & os, const Time & t)
{
    os<<t.hours<<" hours, "<<t.minutes<<" minutes\n";
    return os;
}


Вот ошибки:

g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\m.h(16) : error C2270: '+' : modifiers not allowed on nonmember functions
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\m.h(17) : error C2270: '-' : modifiers not allowed on nonmember functions
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\m.h(18) : error C2270: '*' : modifiers not allowed on nonmember functions
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\11.1.cpp(29) : error C2270: '+' : modifiers not allowed on nonmember functions
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\11.1.cpp(37) : error C2270: '-' : modifiers not allowed on nonmember functions
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\11.1.cpp(47) : error C2270: '*' : modifiers not allowed on nonmember functions
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\11.1.cpp(49) : warning C4244: 'initializing' : conversion from 'double' to 'long', possible loss of data
menu.cpp
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\m.h(16) : error C2270: '+' : modifiers not allowed on nonmember functions
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\m.h(17) : error C2270: '-' : modifiers not allowed on nonmember functions
g:\documents and settings\pycha.pycha-1366613\мои документы\visual studio 2008\projects\11.1\11.1\m.h(18) : error C2270: '*' : modifiers not allowed on nonmember functions
Generating Code...
Build log was saved at "file://g:\Documents and Settings\pycha.PYCHA-1366613\Мои документы\Visual Studio 2008\Projects\11.1\11.1\Debug\BuildLog.htm"
11.1 - 9 error(s), 1 warning(s)

Что тут не так: ведь вроде обьявил правильно. smile 

Автор: Void 10.7.2008, 20:17
Цитата
modifiers not allowed on nonmember functions

Убрать const с объявлений операторов, это не методы класса и смысла он не имеет.

Автор: pycha 11.7.2008, 00:04
да действительно заработало. Я думал что const будет давать гарантию что не будет изминений в передаваемых класах. Не думал что в таких случаях они будут лишние...

Автор: bsa 11.7.2008, 09:59
pycha, модификатор const в конце метода нужен чтобы показать, что метод не меняет класс, так как никак иначе это указать нельзя. Просто каждому нестатическому методу первым параметром неявно передается указатель на объект класса. Вот const и относится к нему.
Когда ты пишешь не методы, то ты можешь легко сам вручную указать что у тебя указывает на константу, а что нет.

Автор: pycha 12.7.2008, 11:08
теперь понятно

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)