C++面向对象入门(十九)友元类

 

友元类: 在A类中使用friend关键字声明B类, 则称B类为A类的友元类, 可以在B类内部访问A类的私有成员
语法:
class A{
  friend class B;
};
inventory n.详细目录;库存;

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

using namespace std;

const int MAXSIZE = 100;

/**
 * 友元类: 在A类中使用friend关键字声明B类, 则称B类为A类的友元类, 可以在B类内部访问A类的私有成员
 * 语法:
 * class A{
 *  friend class B;
 * };
 * inventory 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) {}

    string getInfo() {
        return "Item{name:" + name + ", price:" + to_string(price) + ", quantity:" + to_string(quantity) + "}";
    }
};

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



class Store {
    //声明Boss类为Store类的友元类
    friend class Boss;
private:
    double balance;
    Item itemList[MAXSIZE];
    Goods menu[MAXSIZE];
    int goodsQuantity;
public:
    const string name = "MINI STORE";

    Store() {

    }

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

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

};

class Boss {
private:
    Store store;
public:
    Boss(const Store& store): store(store) {}

    void viewInventory() {
        //在Store类的友元类Boss类内访问Store类的私有成员
        for (int i = 0; i < store.goodsQuantity; ++i) {
            cout << store.itemList[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};
    Boss boss(store);
    boss.viewInventory();
}
int main() {
    test1();
    system("pause");

    return 0;
}

 

 
posted @ 2020-08-20 14:58  DNoSay  阅读(292)  评论(0)    收藏  举报