您的位置:首页 > 其它

友元关系与继承以及基类派生类定义构造函数时应该注意的事项

2014-12-25 21:42 435 查看
1、像其他类一样,基类或派生类可以使其他类或函数成为友元,友元可以访问类的private,protected成员;

2、友元关系不能继承。基类的友元对派生类的成员没有特殊访问权限,如果基类被授予友元关系,则只有基类具有特殊的访问权限,该基类的派生类不能访问授予友元关系的类;

3、如果派生类想要将自己成员的访问权限授予基类的友元,则必须显示的在派生类中指定友元关系即包含friend字段;

4、如果类有派生类则需指定默认的构造函数,因为在调用派生类构造函数时,会先调用基类的默认构造函数;

5、友元关系不能继承;

c++第四版 书本例子

#include <iostream>

using namespace std;

class Base

{

    public:

    friend class Frnd;

    Base(int init):i(init){}

    protected:

    Base(){}//如果有派生类则需指定默认的构造函数,因为在调用派生类构造函数时,会先调用基类的默认构造函数

    int i;

};

class D1 : public Base

{

    friend class Frnd;//派生类中显示指定友元关系

    public:

    D1(int init1,int k):j(init1),m(k){}

    protected:

    int j;

    int m;

};

class Frnd

{

    public:

    int mem(Base b)

    {

        return b.i;

    }

    int men(D1 d)//不要写成D1 d(int,int)

    {

        return d.i;

    }

};

int main()

{

    Base base(1);

    D1 d1(1,1);

    //base.i = 1;

    Frnd frnd;

    cout << frnd.mem(base)<< endl;

    cout << frnd.men(d1)<< endl;

    //cout << "Hello world!" << endl;

    return 0;

}

/*class D2 :public Frnd

{

public:

int mem(Base b){ return b.i;}//友元关系不能继承

}*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐