从相关类访问私有成员数据

Accessing private member data from related class

本文关键字:成员 数据 访问      更新时间:2023-10-16

我正在尝试为我的OO类编写两个类,销售和注册。下面是两个标题。

销售标题:

enum ItemType {BOOK, DVD, SOFTWARE, CREDIT};
class Sale
{
public:
Sale();         // default constructor, 
            // sets numerical member data to 0
void MakeSale(ItemType x, double amt);  
ItemType Item();        // Returns the type of item in the sale
double Price();     // Returns the price of the sale
double Tax();       // Returns the amount of tax on the sale
double Total();     // Returns the total price of the sale
void Display();     // outputs sale info (described below)
private:
double price;   // price of item or amount of credit
double tax;     // amount of sales tax (does not apply to credit)
double total;   // final price once tax is added in.
ItemType item;  // transaction type
};

寄存器标头:

class Register{
public:
Register(int ident, int amount);
~Register();
int GetID(){return identification;}
int GetAmount(){return amountMoney;}
void RingUpSale(ItemType item, int basePrice);
void ShowLast();
void ShowAll();
void Cancel();
int SalesTax(int n);
private:
int identification;
int amountMoney;
int listSize;
int numSales;
Sale* sale;
};

在 Register 类中,我需要保存 Sale 对象的动态数组。我能够做到这一点。我的问题是"注册"中的RingUpSale()函数。我需要能够从该功能访问和修改"销售"的私人会员数据。例如:

sale[numSales]->item = item;
    sale[numSales]->total = basePrice; // Gets an error
    if(item == CREDIT){
            sale[numSales]->tax = 0; // Gets an error
            sale[numSales]->total = basePrice; // Gets an error
            amountMoney -= basePrice;
    }
    else {
        sale[numSales]->tax = 0.07*basePrice; // Gets an error
        sale[numSales]->total = (0.07*basePrice)+basePrice; // Gets an error
        amountMoney += basePrice;
    }

我不知道如何使这种访问成为可能。也许通过继承或朋友结构?

在你对这个设计大发雷霆之前,请记住这是为了家庭作业,所以有愚蠢的限制。 其中之一是我无法修改我所写内容的"Sale.h"。而且我只能在"Register.h"中添加更多私有函数。

RingUpSale() 函数说明:

  • 铃声促销此函数允许将销售的项目类型和基价作为参数传入。这函数应将销售存储在销售列表中,并且应更新适当收银。购买的物品将向收银机添加金钱。记住销售税必须添加到任何已售商品的基本价格中。如果销售类型为信用,则您应从登记册中扣除金额。

还有这个:

-(提示:请记住,在寄存器中,您保留了一个动态的 Sale 对象数组。这意味着这些函数中的大多数都将使用此数组来完成它们的工作 - 它们也可以调用销售类成员函数)。

make getter and setters:

int getX() { return _x; } void setX(int x_) { _x = x_; } private: int _x; };

x 是你想要的变量

看起来Sale::MakeSale()函数旨在处理这些税收计算细节。给定一个项目和一个基本价格,它将计算税款(如有必要)并更新total值。

(我假设虽然你不能修改Sale.h,但你可以实现Sale.cpp