c++ - 从相关类访问私有(private)成员数据

标签 c++ inheritance

我正在尝试为我的 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() 函数。我需要能够从该函数访问和修改“销售”的私有(private)成员数据。例如:

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;
    }

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

在你提示这个设计之前,请记住这是为了家庭作业,所以有一些愚蠢的限制。其中之一是我无法根据我编写的内容修改“Sale.h”。而且我只能在'Register.h'中添加更多私有(private)函数。

RingUpSale()函数说明:

  • 环购 此函数允许将销售的商品类型和基本价格作为参数传入。这 函数应该将销售存储在销售列表中,并且应该更新 收银机适当。购买的元素会将钱添加到寄存器中。请记住 销售税必须添加到任何销售商品的基本价格中。如果销售类型是 CREDIT,那么您 应从登记册中扣除金额。

还有这个:

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

最佳答案

制作 getter 和 setter:

int getX() { return _x; } void setX(int x_) { _x = x_; } 私有(private)的: 诠释_x; };

x 是你想要的变量

关于c++ - 从相关类访问私有(private)成员数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11172763/

相关文章:

c++ - 在没有任何条件语句或变量捕获的情况下使用逻辑运算符

c++ - 在 c'tor 初始化器列表中将临时绑定(bind)到 const 引用

java - 具有额外属性的子类构造函数

C++ 引用父类(super class)中的子类

java - 为什么我的方法调用转换不能将 2d ArrayList 转换为 2d List?

c++ - 如何在C++中正确继承基类并覆盖虚函数

c++ - 如何声明指向多维数组的指针数组

c++ - 使用帧缓冲区对象作为纹理的视觉问题

c# - 如何将结构数组从 C++ dll 返回到 C#

java - 从其内部类访问类对象