C++面向对象入门(十八)全局友元函数

 

全局友元函数: 在类内部声明且使用friend关键字修饰, 在类外和函数外定义的全局函数, 可以访问类中的私有成员
语法:
1, 声明(必须在类内部):
friend 返回值类型 函数名(参数列表);
2, 定义(在类外)
返回值类型 函数名(参数列表) {
函数体
}
quantity n.量,数量;总量;
explicitly adv.明确地;明白地;
grape n.葡萄;

示例代码:
#include <iostream>
#include <string>

using namespace std;

const int MAXSIZE = 100;

/**
 * 全局友元函数: 在类内部声明且使用friend关键字修饰, 在类外和函数外定义的全局函数, 可以访问类中的私有成员
 * 语法:
 * 1, 声明(必须在类内部):
 * friend 返回值类型 函数名(参数列表);
 * 2, 定义(在类外)
 * 返回值类型 函数名(参数列表) {
 * 函数体
 * }
 * quantity n.量,数量;总量;
 * explicitly adv.明确地;明白地;
 * grape n.葡萄;
 */
class Item {
    string name;
    double price;
    int quantity;
public:
    Item() {

    }

    Item(const string &name, double price, int quantity) : name(name), price(price), quantity(quantity) {}
};

struct Goods {
    string name;
    double price;
    string getInfo() {
        return "name: " + name + ", price: " + to_string(price);
    }
};



class Store {
private:
    double balance;
    Item itemList[MAXSIZE];
    Goods menu[MAXSIZE];
    int goodsQuantity;
public:
    const string name = "MINI STORE";

    Store() {

    }

    Store(double balance, Item *itemList, Goods *menu, int goodsQuantity) : balance(balance),
                                                                            goodsQuantity(goodsQuantity) {
        for (int i = 0; i < goodsQuantity; ++i) {
            this->itemList[i] = itemList[i];
            this->menu[i] = menu[i];
        }
    }

    ~Store() {
        cout << "Close the Store" << endl;
    }

    friend void readMenu(Store &store);
};

void readMenu(Store &store) {
    //使用友元函数在类外访问类的私有成员
    for (int i = 0; i < store.goodsQuantity; ++i) {
        cout << "goods{" << store.menu[i].getInfo() << "}" << endl;
    }
}

void test1() {
    Item itemList[] = {Item("apple",2.5,10),Item("watermelon",1.2,100),Item("grape",10,15)};
    Goods menu[] = {Goods{"apple", 2.5}, Goods{"watermelon", 1.2}, Goods{"grape", 10}};
    Store store = {100, itemList, menu,3};
    readMenu(store);
}

int main() {
    test1();
    system("pause");

    return 0;
}

 



posted @ 2020-08-20 14:29  DNoSay  阅读(297)  评论(0编辑  收藏  举报