1、友元类

#include <iostream>
#include <string>
using namespace std;

class Librarian;

// 图书馆类,拥有珍贵的藏书
class Library 
{
friend class Librarian;  // 声明图书管理员类为友元类

private:
    string secretDoc = "Original copy";
};

// 图书管理员类,能够访问图书馆的藏书
class Librarian 
{
public:
    void access(const Library& lib) 
    {
        cout << "Librarian have accessed:  " << lib.secretDoc<< endl;
    }
};

int main ( int argc, char *argv[] ) 
{
    Library library;
    Librarian librarian;
    librarian.access(library); // 图书管理员访问了图书馆的珍贵藏书
    return 0;
}

 

2、友元函数

(1) 全局友元函数

#include <iostream>
#include <string>
using namespace std;

class Family 
{
friend void Postman(Family&); // 声明邮递员为友元,赋予其访问信箱的权限

private:
    string mailBoxStatus = "Now it is empty!";
};

// 全局友元函数,邮递员可以访问家庭的私有信箱
void Postman(Family &f) 
{
    cout << "Postman checks the mailbox: " << f.mailBoxStatus << endl;
}

int main( int argc, char* argv[] ) 
{
    Family family;
    Postman(family);  // 邮递员访问家庭的信箱
    return 0;
}

 

(2) 成员友元函数

#include <iostream>

class Garden;

// 园艺师类
class Gardener 
{
public:
    void careForPlant(const Garden& g);
};

// 花园类,拥有一些稀有植物
class Garden 
{
private:
    void rarePlant() const 
    {
        std::cout << "Watering a rare plant." << std::endl;
    }

    // 声明Gardener的特定成员函数为友元
    friend void Gardener::careForPlant(const Garden&);
};

// Gardener 类成员函数定义
void Gardener::careForPlant(const Garden& g) 
{
    std::cout << "Gardener is caring for a plant." << std::endl;
    g.rarePlant(); // 访问并照顾花园的稀有植物
}

int main(int argc, char* argv[]) 
{
    Garden garden;
    Gardener gardener;
    gardener.careForPlant(garden); // 园艺师照顾花园的稀有植物

    return 0;
}

 

3、友元运算符

#include <iostream>
using namespace std;

class Point 
{
private:
    int x, y;
public:
    Point(int x, int y) : x(x), y(y) {}

    // 声明友元运算符
    friend ostream& operator<<(ostream& os, const Point& p);
};

// 实现运算符重载
ostream& operator<<(ostream& os, const Point& p) 
{
    os << "Point(" << p.x << ", " << p.y << ")";
    return os;
}

int main() 
{
    Point p(3, 4);
    cout << p << endl;  // 输出: Point(3, 4)
    return 0;
}

 

posted on 2025-05-05 11:11  轩~邈  阅读(18)  评论(0)    收藏  举报