2013-06-26 62 views
1
#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(); 
} 

如何使用朋友类和朋友功能?请帮助我。我有很多类似的错误:如何使用朋友功能或朋友类?

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 

回答

4

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(); 
} 
+0

你需要使cout1返回一些东西来编译 – doctorlove

+0

谢谢,为什么你不应该复制粘贴的另一个例子。 (这是关于我吸取教训的时间) – RobbieE

+0

非常感谢。 。你可以请朋友成员fuc帮忙。 。 – brownKnight

1

最好的解决方案是让你从基类访问的字段受到保护,而不是私人的。如果您想使用friend,则必须将CDerived作为CBase类的朋友。

+0

请注意,没有办法让'CDerived :: cout1'成为'CBase'的朋友;它会引起相互依赖的定义。 – Angew

+0

@Angew true。我将删除那 –

1

当你说

class CDerived : public CBase 
{ 

    public: 
    friend class CBase; 

这意味着,CBase访问CDerived的私有成员,而不是周围的其他方式。根据你的设计,或许最好让这些成员protected。否则,您需要声明CDerived作为CBase的朋友。

0

当你写

friend class CBase; 

这意味着CBase类可以访问将CDerived的私有方法。什么你想在这里做的是写

friend class CDerived 
在CBase的

,所以如果你想B类绕过A类的封装,然后A必须申报B如将CDerived可以使用CBase的