【问题标题】:Friend Function Unable to access Private data member好友功能无法访问私有数据成员
【发布时间】:2017-11-06 17:20:31
【问题描述】:

我正在尝试编写朋友功能以及时添加分钟,然后相应地更改小时 例如:如果时间 t3(11,58,0) 添加分钟(t3,10); t3.print() 应该给 12:08:00 PM 下面是我尝试编译时给出的代码,'分钟'是'时间'的私有成员。请让我知道我在这里做了什么定义错误的函数。

/*Header File for Time */
Time.h

#ifndef RATIONALNO_TIME_H
#define RATIONALNO_TIME_H
#include<iostream>
using namespace std;
class Time{
    friend void addMinutes(Time&,const int&);
public:
    Time(const int&,const int&,const int&);
    void print()const;
private:
    int hour;
    int minute;
    int second;
};
#endif //RATIONALNO_TIME_H

/*Source File*/
Time.cc


#include "Time.h"
Time::Time(const int& h,const int& m,const int& s)
{
    if(h>=0 && h<=23) {
        hour = h;
    }else
        hour=0;
    if(m>=0 && m<=59) {

        minute = m;
    }else
        minute=0;
    if(s>=0 && s<=59) {
        second = s;
    }else second=0;
}

void Time::print() const {

    cout<<hour;
    cout<<minute;
    cout<<second<<endl;
    cout<<((hour==0||hour==12)?12:hour%12)<<":"<<minute<<":"<<second<<(hour<12?"AM":"PM")<<endl;
}

void addMinutes(Time& time1,int & m)
{
    int hr;
   if(time1.minute+m>59)
   {
       hr=time1.hour+1;
   }
}

int main()
{
    Time t1(17,34,25);
    t1.print();

    Time t3(11,58,0);
    t3.print();
    addMinutes(t3,10);
    t3.print();
}

【问题讨论】:

  • 仔细阅读朋友声明的原型和定义。
  • 并且不要通过 const 引用传递像 int 这样的原语。这是毫无意义的悲观。

标签: c++ private-members friend-function


【解决方案1】:

你声明你的朋友函数:

friend void addMinutes(Time&,const int&); // (Time&, const int&) <- const int

但是用以下方式定义它:

void addMinutes(Time& time1,int & m)... // (Time& time1, int & m) <- non-const int

将以上内容改为:

friend void addMinutes(Time &, int);

void addMinutes(Time &time1, int m)....

相应地,它会编译。

【讨论】:

    猜你喜欢
    • 2014-08-21
    • 2021-08-05
    • 2021-01-02
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多