为了账号安全,请及时绑定邮箱和手机立即绑定

vs 2013 友元函数不可访问私有函数 但编译可通过 求解释

https://img1.sycdn.imooc.com//5cc40e7200018f7c15930774.jpg

不可访问 为什么还能编译通过?

正在回答

6 回答

在Match.h中不能包含Time.h,只能用class Time预声明有这个类,我就是去掉time的头文件,和老师一样就行了

0 回复 有任何疑惑可以回复我~

我遇到过这个问题,就是因为你的time.h中没有加 using namespace std; 导致的, 但我不知道为什么?

0 回复 有任何疑惑可以回复我~
你的并没有编译通过
很可能时你声明友元函数时名字与Match里不一致

Demo.cpp

#include<iostream>
#include<stdlib.h>
#include"Time.h"
#include "Match.h"
using namespace std;
//void printTime(Time &t);
int main(void)
{
Time t(6,34,25);
    Match m;
m.PrintTime(t);
    system("pause");
    return 0;
}
//void printTime(Time &t)
//{
//    cout<<t.m_iHour<<":"<<t.m_iMinute<<":"<<t.m_iSecond<<endl;
//}

Match.h

#ifndef STUDENT_H
#define STUDENT_H
class Time;
class Match
{
public:
    void PrintTime(Time &t);
};
#endif

Match.cpp

#include"Match.h"
#include"Time.h"
#include<iostream>
using namespace std;
void Match::PrintTime(Time &t)
{
cout<<t.m_iHour<<":"<<t.m_iMinute<<":"<<t.m_iSecond<<endl;
}

Time.h

#ifndef TIME_H
#define TIME_H
#include "Match.h"
#include<iostream>
using namespace std;
class Time
{
friend void Match::PrintTime(Time &t);
public:
    Time(int hour,int min,int sec);
private:
    int m_iHour;
    int m_iMinute;
    int m_iSecond;
};
#endif

Time.cpp

#include "Time.h"
Time::Time(int hour,int min,int sec)
{
    m_iHour=hour;
    m_iMinute=min;
    m_iSecond=sec;
}


0 回复 有任何疑惑可以回复我~

执行不变错。是为什么呢?

0 回复 有任何疑惑可以回复我~

+1一样

0 回复 有任何疑惑可以回复我~

编译没有通过啊?你应该是其他地方有问题

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
C++远征之模板篇
  • 参与学习       91174    人
  • 解答问题       318    个

本C++教程力求即学即会,所有知识以实践方式讲解到操作层面

进入课程

vs 2013 友元函数不可访问私有函数 但编译可通过 求解释

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信