[英]Accessing private member data from related class
我正在嘗試為我的OO類編寫兩個類,即Sale和Register。 這是兩個標題。
銷售標題:
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對象數組。這意味着這些函數中的大多數將使用該數組來完成其工作-並且它們還可以調用Sale類成員函數)。
產生吸氣劑和吸氣劑:
int getX() { return _x; } void setX(int x_) { _x = x_; } private: int _x; };
x是您想要的變量嗎
看起來Sale::MakeSale()
函數旨在處理這些稅收計算詳細信息。 給定項目和底價,它將計算稅款(如有必要)並更新total
價值。
(我假設盡管您不能修改Sale.h
,但是可以實現Sale.cpp
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.