访问私有对象数据时出现问题
Trouble accessing private object data
所以我正在为我的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"
。
-
在你的最后一个片段中,你说
if(item == 'CREDIT')
但这是错误的,原因有很多。单引号仅用于单个字符。"item"的类型是"ItemType",它是一个枚举。您应该使用if(item == CREDIT)
因为 CREDIT 被定义为枚举元素。否则,该语句会导致与您希望它执行的操作无关的行为。 -
我认为最好保持对构造函数的初始化(请参阅列表大小)。
-
您无法从课程外部访问私有成员。你应该要么将代码的某些部分外部化到另一个类,要么提供公共函数,如果需要,可以使用参数进行处理,或者创建友元类(我认为在大多数情况下这是不受欢迎的,因为它是糟糕设计的标志(又名"我不知道如何做X,所以我求助于Y")。
如果您需要更多帮助,也许我明天可以为您想出一些代码,今天有点晚了。
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- HDF5Cpp 扩展复合数据集超板问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 我对数据结构、双向链表有一些问题
- 使用蓝牙组件将数据从Android手机传输到串行设备时出现问题
- Java 客户端C++服务器数据发送/接收问题
- printf 数据类型说明符复杂问题
- 从文件导入数据时遇到问题.我有一个没完没了的循环
- 对于这个问题,是否有更好的数据结构和算法选择
- 使用SSE内部函数复制少量数据时出现问题
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- 面对迭代矢量<矢量<string>>和打印数据的问题
- C++中从客户端到服务器的数据传输问题
- 将此类数据作为字符串进行比较时出现问题
- 线程清理器检测到数据争用,问题出在哪里?
- 如何解决在 clr 项目的特定文件中写入数据的问题?
- C++奇怪的问题.数据成员超出范围
- C 的多态性问题 - 数据覆盖
- 面试问题——数据结构