c++ 友元函数定义时 参数引用对象 出错
头文件#include<iostream>usingnamespacestd;classtime{private:intminutes;inthours;public:t...
头文件
#include<iostream>
using namespace std;
class time
{
private:
int minutes;
int hours;
public:
time();
time(int Minutes,int Hours);
friend time operator* (int n,time &);
friend ostream & operator<< (ostream &,time &);
void reset(int Minutes,int Hours);
void show();
};
file1.cpp
#include<iostream>
#include"operator.h"
time::time()
{
minutes=0;
hours=0;
}
time::time(int Minutes,int Hours)
{
minutes=Minutes;
hours=Hours;
}
time operator* (int n,time & t)
{
time multiply;
multiply.minutes = t.hours*60*n + t.minutes*n;
multiply.hours = multiply.minutes / 60;
multiply.minutes =multiply.minutes % 60;
return multiply;
}
ostream & operator<< (ostream & co,time & t)
{
co<<"hours : "<<t.hours;
return co;
}
void time::reset(int Minutes,int Hours)
{
minutes = Minutes;
hours = Hours;
}
void time::show()
{
cout<<"minutes : "<<minutes<<endl;
cout<<"hours : "<<hours<<endl;
} //此处出错。
error:
E:\c++\c++ 工程\a1123\operatora.cpp(60) : error C2248: 'hours' : cannot access private member declared in class 'time'
e:\c++\c++ 工程\a1123\operator.h(8) : see declaration of 'hours' 展开
#include<iostream>
using namespace std;
class time
{
private:
int minutes;
int hours;
public:
time();
time(int Minutes,int Hours);
friend time operator* (int n,time &);
friend ostream & operator<< (ostream &,time &);
void reset(int Minutes,int Hours);
void show();
};
file1.cpp
#include<iostream>
#include"operator.h"
time::time()
{
minutes=0;
hours=0;
}
time::time(int Minutes,int Hours)
{
minutes=Minutes;
hours=Hours;
}
time operator* (int n,time & t)
{
time multiply;
multiply.minutes = t.hours*60*n + t.minutes*n;
multiply.hours = multiply.minutes / 60;
multiply.minutes =multiply.minutes % 60;
return multiply;
}
ostream & operator<< (ostream & co,time & t)
{
co<<"hours : "<<t.hours;
return co;
}
void time::reset(int Minutes,int Hours)
{
minutes = Minutes;
hours = Hours;
}
void time::show()
{
cout<<"minutes : "<<minutes<<endl;
cout<<"hours : "<<hours<<endl;
} //此处出错。
error:
E:\c++\c++ 工程\a1123\operatora.cpp(60) : error C2248: 'hours' : cannot access private member declared in class 'time'
e:\c++\c++ 工程\a1123\operator.h(8) : see declaration of 'hours' 展开
1个回答
追问
他说的第一种方法没明白 能具体点吗?
追答
在头文件中类定义之前将类和友元操作符函数的原型特别声明一下,也就是将头文件修改如下(实现文件”.cpp”不用作任何修改):
修改后的头文件
#include
using namespace std;
-----------------------------
//预先声明
class time;
ostream & operator<< (ostream &,time &);
----------------------------
class time
{
private:
int minutes;
int hours;
public:
time();
time(int Minutes,int Hours);
friend time operator* (int n,time &);
friend ostream & operator<< (ostream &,time &);
void reset(int Minutes,int Hours);
void show();
};
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询