#include <iostream>
using namespace std;
class CBase
{
public:
int a;
int b;
private:
int c;
int d;
protected:
int e;
int f;
//friend int cout1();
};
class CDerived : public CBase
{
public:
friend class CBase;
int cout1()
{
cout << "a" << endl;
cin >> a;
cout << "b" << endl;
cin >> b;
cout << "c" << endl;
cin >> c;
cout << "d" << endl;
cin >> d;
cout << "e" << endl;
cin >> e;
cout << "f" << endl;
cin >> f;
cout << a << "" << b << "" << c << "" << d << "" << e << "" << f << "" << endl;
}
};
int main()
{
CDerived chi;
chi.cout1();
}如何使用friend类和friend函数?请帮帮我。我有很多类似的错误:
c6.cpp: In member function int CDerived::cout1():
c6.cpp:10: error: int CBase::c is private
c6.cpp:30: error: within this context
c6.cpp:11: error: int CBase::d is private
c6.cpp:32: error: within this context
c6.cpp:10: error: int CBase::c is private
c6.cpp:37: error: within this context
c6.cpp:11: error: int CBase::d is private
c6.cpp:37: error: within this context发布于 2013-06-26 16:43:13
CDerived无法访问CBase的私有成员。你和它做朋友与否都无关紧要。如果你想允许这样的访问,你必须让CBase声明友好关系。
#include <iostream>
using namespace std;
class CDerived; // Forward declaration of CDerived so that CBase knows that CDerived exists
class CBase
{
public:
int a;
int b;
private:
int c;
int d;
protected:
int e;
int f;
friend class CDerived; // This is where CBase gives permission to CDerived to access all it's members
};
class CDerived : public CBase
{
public:
void cout1()
{
cout<<"a"<<endl;
cin>>a;
cout<<"b"<<endl;
cin>>b;
cout<<"c"<<endl;
cin>>c;
cout<<"d"<<endl;
cin>>d;
cout<<"e"<<endl;
cin>>e;
cout<<"f"<<endl;
cin>>f;
cout<<a<<""<<b<<""<<c<<""<<d<<""<<e<<""<<f<<""<<endl;
}
};
int main()
{
CDerived chi;
chi.cout1();
}发布于 2013-06-26 16:39:52
对您来说,最好的解决方案是使您从基类访问的字段受保护,而不是私有。不过,如果您想使用friend,则必须使CDerived成为CBase类的友好类。
发布于 2013-06-26 16:40:49
当你说
class CDerived : public CBase
{
public:
friend class CBase;这意味着CBase可以访问CDerived的私有成员,而不是相反。根据您的设计,可能将这些成员设置为protected更好。否则,您需要将CDerived声明为CBase的朋友。
https://stackoverflow.com/questions/17315265
复制相似问题