C++关于友元函数问题(VS2013编译环境提示错误)
这段代码用VS2013调试出来能够有黑窗口,且正常运行,但是VS2013总是提示错误,说是Date类的month,day,year不可访问,他们虽然声明为private,...
这段代码用VS2013调试出来能够有黑窗口,且正常运行,但是VS2013总是提示错误,说是Date类的month,day , year不可访问,他们虽然声明为private,但是友元函数不能访问Date类的私有成员吗?
#include
using namespace std;
class Date;
class Time
{
public:
Time(int, int, int);
void display(Date &);
private:
int hour;
int minute;
int sec;
};
class Date
{
public:
Date(int,int,int);
friend void Time::display(Date &);
private:
int month;
int day;
int year;
};
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
sec = s;
}
void Time::display(Date &d)
{
cout << d.month << "/" << d.day << "/" << d.year << endl;
cout << hour << ":" << minute << ":" << sec << endl;
}
Date::Date(int m, int d, int y)
{
month = m;
day = d;
year = y;
}
int main()
{
Time t1(10, 13, 56);
Date d1(10,01,2011);
t1.display(d1);
return 0;
} 展开
#include
using namespace std;
class Date;
class Time
{
public:
Time(int, int, int);
void display(Date &);
private:
int hour;
int minute;
int sec;
};
class Date
{
public:
Date(int,int,int);
friend void Time::display(Date &);
private:
int month;
int day;
int year;
};
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
sec = s;
}
void Time::display(Date &d)
{
cout << d.month << "/" << d.day << "/" << d.year << endl;
cout << hour << ":" << minute << ":" << sec << endl;
}
Date::Date(int m, int d, int y)
{
month = m;
day = d;
year = y;
}
int main()
{
Time t1(10, 13, 56);
Date d1(10,01,2011);
t1.display(d1);
return 0;
} 展开
展开全部
楼主,你的这种写法看上起是比较老式的写法了,此种情况我建议采用友元函数共享类之间的私有成员数据。具体写法如下:
// 我个人认为类的提前引用更适用于友元函数共享两个类之间的私有成员数据,
// 而不是将某个类的成员函数声明为另一个类友元函数,因为那样显得有点多
// 此一举,注意此错误并非VS2013智能提示存在问题。智能提示能够检测得出来,
// 是因为这种写法微软是不赞成的。而我下面的做法是正确的。
class Date;
class Time
{
public:
Time(int, int, int);
friend void display(Date &, Time&);
private:
int hour;
int minute;
int sec;
};
class Date
{
public:
Date(int, int, int);
friend void display(Date &,Time&);
private:
int month;
int day;
int year;
};
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
sec = s;
}
void display(Date &d, Time &t)
{
cout << d.month << "/" << d.day << "/" << d.year << endl;
cout << t.hour << ":" << t.minute << ":" <<t.sec << endl;
}
Date::Date(int m, int d, int y)
{
month = m;
day = d;
year = y;
}
int main()
{
Time t1(10, 13, 56);
Date d1(10, 01, 2011);
display(d1,t1);
return 0;
}
2015-01-25
展开全部
IntelliSense 的话不管它就好了,反正它的BUG不影响编译
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询