注册 登录
编程论坛 C++教室

关于c++友元类的错误

wghost 发布于 2009-10-31 20:23, 529 次点击
//Time.h
class Date;
class Time  
{
public:
    Time(int,int,int );
    void display(const Date&);
    virtual ~Time();
private:
    int hour;
    int minute;
    int sec;

};
//Date.h
class Time;
class Date  
{    friend  class Time;
public:
    Date(int,int,int);

    virtual ~Date();
private:
    int month;
    int day;
    int year;
};
//Time.cpp
Time::Time(int h,int m,int s)
{
 hour=h;
 minute=m;
 sec=s;
}

Time::~Time()
{

}
void display( const Date & d)
{
    cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
    cout<<hour<<"/"<<minute<<"/"<<sec<<endl;
}
//Date.cpp
Date::Date(int m,int d,int y)
{
 month=m;
 day=d;
 year=y;
}

Date::~Date()
{

}
//主函数
#include"Date.h"
#include"Time.h"
int main()
{
    Time t1(10,13,56);
    Date d1(12,15,2004);
    t1.display(d1);
    return 0;
}
我用的是vc++环境为什么总提示下列错误啊,各位高手多指教啊
Compiling...
Time.cpp
D:\c++\ex3_h11\Time.cpp(26) : error C2248: 'month' : cannot access private member declared in class 'Date'
        d:\c++\ex3_h11\date.h(21) : see declaration of 'month'
D:\c++\ex3_h11\Time.cpp(26) : error C2248: 'day' : cannot access private member declared in class 'Date'
        d:\c++\ex3_h11\date.h(22) : see declaration of 'day'
D:\c++\ex3_h11\Time.cpp(26) : error C2248: 'year' : cannot access private member declared in class 'Date'
        d:\c++\ex3_h11\date.h(23) : see declaration of 'year'
D:\c++\ex3_h11\Time.cpp(27) : error C2065: 'hour' : undeclared identifier
D:\c++\ex3_h11\Time.cpp(27) : error C2065: 'minute' : undeclared identifier
D:\c++\ex3_h11\Time.cpp(27) : error C2065: 'sec' : undeclared identifier
Error executing cl.exe.

2 回复
#2
flyingcloude2009-10-31 22:19
void display( const Date & d)
这个应该写成下面这样
void Time::display( const Date & d)

要小心细节啊
#3
wghost2009-11-04 10:33
谢啦!!
1