Toriyung

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

友元函数/类

类的private和protect类型一般来说不可以被外部访问,但可以通过friend标志绕过其限制。

在类中添加友元,相当于安插了一个卧底,可以访问类内私有元素,如下

复制代码
class Box
{
private:
double width; public: friend void printWidth(Box box); friend class BigBox; void setWidth(double wid); }; class BigBox { public : void Print(int width, Box &box) { // BigBox是Box的友元类,它可以直接访问Box类的任何成员 box.setWidth(width); cout << "Width of box : " << box.width << endl; } };
复制代码

因为Box类中添加友类BigBox,所以BigBox可以访问Box类的私有成员   

 

复制代码
class Box
{
private:
double width; public: friend void printWidth( Box box ); void setWidth( double wid ); }; // 成员函数定义 void Box::setWidth( double wid ) { width = wid; } // 请注意:printWidth() 不是任何类的成员函数 void printWidth( Box box ) { /* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */ cout << "Width of box : " << box.width <<endl; }
复制代码

因为Box类中添加友函数printWidth,所以printWidth可以访问Box类中的私有成员:box.width

 

 

需要注意的是,如果需要修改私有类,应该使用指针传递而不是值传递,这点和普通变量是一样的

复制代码
#include<iostream>



    
class MyClass
{
protected:
    int pri;
public:
    static int sta;
    int a;
    char b;

public:
    MyClass();
    ~MyClass();

    void print()
    {
        std::cout << this->pri << std::endl;
    }

    friend void plus(MyClass *MC);
    //int operator >=(MyClass A)
    //{
    //    return A.a + 1;
    //}

private:

};


MyClass::MyClass()
{
    sta++;
    pri = 0;
}

MyClass::~MyClass()
{
}

int MyClass::sta = 0;


void plus(MyClass *MC)  //如果此处使用void plus(MyClass MC){MC.pri = 10}则无法成功修改pri
{    
    MC->pri = 10;
    
}

int main()
{
    MyClass *A1; A1 = new MyClass();
    plus(A1);
    A1->print();

    return 1;

}
复制代码

 

posted on   Toriyung  阅读(41)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示