访问私有对象数据时出现问题

Trouble accessing private object data

本文关键字:问题 数据 对象 访问      更新时间:2023-10-16

所以我正在为我的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 = 5;
int numSales;
Sale* sale;
};

所以我现在正在尝试编写RingUpSale()函数,但我似乎无法访问私有字段。这是我的代码:

void Register::RingUpSale(ItemType item, int basePrice){
if(numSales == listSize){
        listSize += 5;
        Sale * tempArray = new Sale[listSize];
        memcpy(tempArray, sale, numSales * sizeof(Sale));
        delete [] sale;
        sale = tempArray;
    }
    sale[numSales]->item = item; //this works for some reason
    sale[numSales]->total = basePrice; // this doesn't
    if(item == 'CREDIT'){ 
            sale[numSales]->tax = 0; // and this doesn't
            sale[numSales]->total = basePrice; // and neither does this
            amountMoney -= basePrice;
    }
    ++numSales;
}

尝试设置销售对象的总计和税项字段在 Eclipse 中出现错误:

"Field 'total' cannot be resolved"

我不确定为什么会这样或如何解决它。任何帮助将不胜感激。是的,我已经在必要时添加了#include "sale.h"#include "register.h"

  1. 在你的最后一个片段中,你说if(item == 'CREDIT')但这是错误的,原因有很多。单引号仅用于单个字符。"item"的类型是"ItemType",它是一个枚举。您应该使用if(item == CREDIT)因为 CREDIT 被定义为枚举元素。否则,该语句会导致与您希望它执行的操作无关的行为。

  2. 我认为最好保持对构造函数的初始化(请参阅列表大小)。

  3. 您无法从课程外部访问私有成员。你应该要么将代码的某些部分外部化到另一个类,要么提供公共函数,如果需要,可以使用参数进行处理,或者创建友元类(我认为在大多数情况下这是不受欢迎的,因为它是糟糕设计的标志(又名"我不知道如何做X,所以我求助于Y")。

如果您需要更多帮助,也许我明天可以为您想出一些代码,今天有点晚了。