Toriyung

导航

友元函数/类

类的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 2023-02-25 09:21  Toriyung  阅读(29)  评论(0编辑  收藏  举报