首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

为什么小弟我定义的友元操作符不能访问私有变量

2012-02-08 
为什么我定义的友元操作符不能访问私有变量!#include string#include iostreamusing namespace stdcl

为什么我定义的友元操作符不能访问私有变量!
#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; } 

热点排行