2012-06-23 89 views
0

所以我正在爲我的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"

+3

這就是讓他們成爲'私人'的想法,這樣別人就不會混淆他們了。'MakeSale'函數不能幫助你嗎? –

回答

0
  1. 在你最後的片段中,你說if(item == 'CREDIT'),但這是錯誤的,原因很多。單引號僅用於單個字符。 'item'是類型'ItemType',它是一個枚舉。您應該使用if(item == CREDIT),因爲CREDIT被定義爲枚舉元素。否則這種說法會導致與你想要做的事無關的行爲。

  2. 我認爲最好對構造函數進行初始化(請參閱listSize)。

  3. 您無法從課外訪問私人會員。您應該將代碼的某些部分外部化到另一個類中,使公共函數可用,並根據需要使用參數進行處理,或者創建好友類(我認爲這在大多數情況下都是不被接受的,因爲它是壞設計的標誌(又名「我不知道該怎麼做X,所以我求助於Y「)。

如果您需要更多的幫助,也許我能想出明天你一些代碼,這是一個有點晚了今天。

+0

我想他可能希望我們讓Sale朋友的某些東西去註冊,或者可能從Sale中繼承某些東西到Registe河我不能添加公共功能。 –

+0

爲什麼不使用MakeSale()? – ApplePie