返回

C++ 核心 4.4 友元

发布时间:2023-02-15 21:17:44 255
# 数据

4.4 友元

一种权限控制的方法,让类外的一些函数或类能访问类的私有属性。 关键字为friend 友元的三种形式: 全局函数friend void goodGay(Building &building);friend class GoodGay 成员函数friend void GoodGay::visit();

4.4.1 全局函数 友元

class Building{
    //友元声明
    friend void goodGay(Building &building);
public:
    Building(){
        m_SittingRoom = "客厅";
        m_BedRoom = "卧室";
    }
public:
    string m_SittingRoom;
private:
    string m_BedRoom;
};

//全局函数

void goodGay(Building &building){
    cout<< building.m_SittingRoom<

4.4.2 类做友元

class Building;
class GoodGay{
public:
    GoodGay();
    void visit();
    Building * building; 
};


class Building{
    //声明GoodGay类是 本类的友元
    friend class GoodGay;
public:
    Building();
public:
    string m_SittingRoom;
private:
    string m_BedRoom;
};

//类外实现:
Building::Building()
{
    m_SittingRoom = "客厅";
    m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
    building = new Building;
}
void GoodGay::visit()
{
    cout<m_SittingRoom;
    cout<m_BedRoom;
}

4.4.3 成员函数做友元

只让某个类的某个成员函数 可以访问自己的私有属性。 在类中声明该类的该函数为友元: 例如,让GoodGay的visit()可以访问Building的私有属性:

class Building
{
friend void GoodGay::visit();
public:
...
private:
...
};

4.5 运算符重载

对已有的运算符重新定义,赋予其另一种功能以适应不同的数据类型。

4.5.1 加号运算符重载

operator+ 通过成员函数重载

Person operator+(Person &p){
    Persom temp;
    temp.A = this->A + p.A;
    temp.B = this->B + p.B;
    return temp;
}

通过全局函数重载

Person operator+(Person &p1, Person &p2){
    Persom temp;
    temp.A = p1.A + p2.A;
    temp.B = p1.B + p2.B;
    return temp;
}

然后可以使用:

Person p3 = p1 + p2 ; //调用重载的operator+

4.5.2 <<左移运算符重载

输出对象。 通过全局函数重载:

ostream & operator<<(ostream& out, Person &p) {
    out<

又因为我们一般将属性设置为私有,所以为了让这个全局函数能访问私有属性,还要将它设置为友元。

4.5.3 递增运算符重载

MyInteger& operator++()

后++,用int做占位参数,区分前++和后++。 MyInteger operator++(int)

MyInteger operator++(int){
    MyInteger temp = *this;
    n_Num ++;
    return temp;
}

将++改为--就是自减运算符。

4.5.4 赋值运算符重载

Person& operator=(Person &p)

解决浅拷贝问题。自己在赋值运算符中使用深拷贝(申请内存)

4.5.5 关系运算符重载

bool operator==(Person &p) bool operator!=(Person &p)

4.5.6 函数调用运算符重载

括号重载 operator() 也称仿函数。 写法灵活。

class MyPrint{
public:
    //重载()
    void operator()(string test){
        cout << test << endl; 
    }

};
...
MyPrint mprint;
mprint("hello"); //使用类似函数调用,因此称为仿函数
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
C++ 核心4.3 C++ 对象模型和this 指针 2023-02-15 20:38:29