为什么我定义的友元操作符不能访问私有变量!
#include <string>
#include <iostream>
using namespace std;
class haha
{
friend ostream&
operator<<(ostream& ,const haha &) ;
public:
haha():m(1),y(2008),d(10)
{
}
private:
int m;
int d;
int y;
};
class CheckoutRecord
{
friend ostream&
operator<<(ostream&,const CheckoutRecord &);
private:
double book_id;
string title;
haha date_borrowed;
haha date_due;
};
std::ostream&
operator<<(ostream& out,const CheckoutRecord &s)
{
out<<s.book_id<<s.title
<<s.date_borrowed<<s.date_due;
return out;
}
void main()
{
CheckoutRecord a;
cout<<a.book_id;
return;
}
error C2248: 'book_id' : cannot access private member declared in class 'CheckoutRecord'
[解决办法]
这和友元没有什么关系啊,你这是在直接访问私有变量,当然报错了
[解决办法]
- C/C++ code
void main() { CheckoutRecord a; cout <<a.book_id; //改为:cout << a;return; }
[解决办法]
- C/C++ code
void main() { CheckoutRecord a; cout < <a.book_id; // 你这里是直接在main函数访问 私有成员, 不是在友元函数中访问!!!!!!return; }