C++面向对象入门(二十)友元成员函数

友元成员函数: 在类A的内部声明一个属于类B的成员函数, 则该成员函数可以访问类A的私有成员
语法:
class A;

class B {
返回值类型 函数名(参数列表);
};

class A {
friend 返回值类型 B::函数名(参数列表);
};


返回值类型 B::函数名(参数列表) {
函数体
}

注意事项:
1, 含有友元成员函数的类需要先定义, 被友元成员函数的访问的类要先声明
2, 在书写有元函数的函数体时, 常常会有报错说使用类未完全定义的类的成员, 故一般的, 在友元成员函数所属的类内只做函数声明,
而在友元成员函数能访问的类定义完成后书写友元成员函数的函数体

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

using namespace std;

const int MAXSIZE = 100;

/**
 * 友元成员函数: 在类A的内部声明一个属于类B的成员函数, 则该成员函数可以访问类A的私有成员
 * 语法:
 * class A;
 *
 * class B {
 *  返回值类型 函数名(参数列表);
 * };
 *
 * class A {
 *  friend 返回值类型 B::函数名(参数列表);
 * };
 *
 *
 * 返回值类型 B::函数名(参数列表) {
 * 函数体
 * }
 *
 * 注意事项:
 * 1, 含有友元成员函数的类需要先定义, 被友元成员函数的访问的类要先声明
 * 2, 在书写有元函数的函数体时, 常常会有报错说使用类未完全定义的类的成员, 故一般的, 在友元成员函数所属的类内只做函数声明, 而在
 * 友元成员函数能访问的类定义完成后书写友元成员函数的函数体
 */
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() const {
        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;
class Employee {
public:
    void viewInventory(const Store &store) ;
};

class Store {
    //声明Boss类的成员函数viewInventory为Store类的友元函数
    friend void Employee::viewInventory(const Store &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 *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;
    }

};

void Employee::viewInventory(const Store &store) {
    //在Boss类内使用Store类的有元成员函数访问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};
    Employee employee;
    employee.viewInventory(store);

}

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

    return 0;
}

 

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