从相关类访问私有成员数据
Accessing private member data from related class
我正在尝试为我的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
。
相关文章:
- 嵌套在类中时无法设置成员数据
- 私有成员数据不可用于公共成员功能
- 我想知道我是否可以将一个类分配给特定的成员数据并创建该类的实例
- 类的成员数据未更新
- 为什么类成员数据必须是静态的才能被模板化类的模板化结构成员访问
- C++:成员不可访问-使用友元函数允许一个类修改另一个类的成员数据
- 如何高效更改向量中所有对象的成员数据?
- constexpr 偏移量,带有指向成员数据的指针
- 从其后声明的另一个成员数据初始化成员数据是否为未定义行为
- C++ 类析构函数删除部分但不是全部成员数据
- 初始化 MFC 中 CFormView 派生类的成员数据
- 覆盖复制/移动分配超载时,我是否需要删除当前的成员数据
- 根据参数设置构造函数的成员数据类型
- 对齐说明符:在类型 / 上 成员数据
- 如何实现ressize()以更改C 中动态成员数据的能力
- C++ 阻止复制成员数据
- 什么是成员数据指针的正确赋值语句
- C++ 在类中使用 strcmp() 处理私有成员数据
- 成员数据在stack实例上覆盖
- 初始化继承的成员数据