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

c++为何小弟我声明了友元,但编译器还是提示:cannot access private member declared in class 'book'

2012-08-25 
c++为何我声明了友元,但编译器还是提示:cannot access private member declared in class book[codeC/C

c++为何我声明了友元,但编译器还是提示:cannot access private member declared in class 'book'
[code=C/C++][/code]
#include <iostream>
#include <string>
using namespace std;

class book
{
public:

book():bookname(" "),number(0),money(0.0){}
book(string& dbookname,int dnumber,double dmoney):bookname(dbookname),number(dnumber),money(dmoney){}

friend istream& operator>>(istream& in,book& inbook);
friend ostream& operator<<(ostream& put,book& putbook);
book& operator+(book& b1)
{
//book result;

bookname+=b1.bookname;
number+=b1.number;
money+=b1.money;
return *this;
}
private:
string bookname;
int number;
double money;


};
istream& operator>>(istream& in,book& inbook)
{
cout<<"Please Enter bookname"<<endl;
in>>inbook.bookname;
in.clear();
cout<<"how much"<<endl;
in>>inbook.number;
in.clear();
cout<<"how money"<<endl;
in>>inbook.money;
in.clear();
return in;
}

ostream& operator<<(ostream& put,book& putbook)
{
put<<"the bookname:"<<putbook.bookname<<endl;
put<<"the number :"<<putbook.number<<endl;
put<<"how money :"<<putbook.money<<endl;
return put;
}

int main()
{
book a("Hacker's story",2,89.56);
book b("c++primer",1,68.2);
book c;
c=a+b;
cout<<c;
return 0;
}


[解决办法]

C/C++ code
class book{public:    book():bookname(" "),number(0),money(0.0){}    book(string& dbookname,int dnumber,double dmoney):bookname(dbookname),number(dnumber),money(dmoney){}    friend istream& operator>>(istream& in,book& inbook);    friend ostream& operator<<(ostream& put,book& putbook);    book& operator+(book& b1)    {        //book result;        bookname+=b1.bookname;        number+=b1.number;        money+=b1.money;        return *this;    }private:    string bookname;    int number;    double money;};istream& operator>>(istream& in,book& inbook){    cout<<"Please Enter bookname"<<endl;    in>>inbook.bookname;    in.clear();    cout<<"how much"<<endl;    in>>inbook.number;    in.clear();    cout<<"how money"<<endl;    in>>inbook.money;    in.clear();    return in;}ostream& operator<<(ostream& put,book& putbook){    put<<"the bookname:"<<putbook.bookname<<endl;    put<<"the number :"<<putbook.number<<endl;    put<<"how money :"<<putbook.money<<endl;    return put;}int _tmain(int argc, _TCHAR* argv[]){    string strName = "Hacker's story";    string strName1 = "c++primer";    book a(strName, 2, 89.56);    book b(strName1, 1, 68.2);    book c;    c=a+b;    cout<<c;    system("pause");    return 0;}
[解决办法]
楼主的代码在VS2010上貌似没啥问题...用的编译器?
[解决办法]
楼主,珍惜生命,远离VC6这个垃圾货。
[解决办法]
探讨
如果是用VC,将友元函数定义放到相应类中!

[解决办法]

探讨

而且现在按照网上的方法 ,搞得我office都用不了额 ,我 晕呀。

[解决办法]
导弹打蚊子.
练习纯C++,装个cygwin就ok了.何必用那盗版的vc.
cygwin g++ 3.4.4只改这三行就通过了.
C/C++ code
string s1="Hacker's story",s2="c++primer";    book a(s1,2,89.56);    book b(s2,1,68.2); 

热点排行