C++有元关系

来源:互联网 发布:mac number 公式 编辑:程序博客网 时间:2024/04/30 02:48

什么是有元关系:

         有元关系是类之间的一种特殊关系,这种关系不仅允许有元类访问对方的public方法和属性.还允许对方访问protected和private方法和属性.

语法:

        friend class XXX

         这条语句可以放在任何地方.包括private里.

一个简单的友元关系:

#include <iostream>#include <string>using namespace std;class AA{public:AA(string theName);private:string name;friend class BB;     //友元关系的使用.};class BB{public:print(AA *p);};AA::AA(string theName){this->name = theName;}BB::print(AA *p){cout<<p->name<<endl;}void main(){AA aa("AA");BB bb = BB();bb.print(&aa);}

如果没加 friend class BB则会报错:

error C2248: 'name' : cannot access private member declared in class 'AA'

see declaration of 'name'

原创粉丝点击