關于我的大學專案的另一個問題!我們正在創建一個收銀機程式,該程式有一個庫存,兩者都保存在各自的頭檔案中,具有自己的類和物件。
這是我們當前的頭檔案迭代,認為它可能因除錯而混亂。
庫存.h:
class inventory
{
protected:
vector <item> itemList;
fstream infile;
public:
void printList();
void fillInventory();
void fileOpen();
};
class item
{
protected:
double price;
string name;
int amount;
friend class inventory;
};
注冊.h:
class cashRegister : protected inventory
{
private:
vector <int> userChoice;
double total = 0;
public:
void input();
void printReceipt();
void calcTotal();
const double getTotal();
};
void cashRegister::input()
{
int temp;
try
{
do
{
cout << "\nPlease select an item using the corresponding item number.\n=> ";
cin >> temp;
if (cin.fail())
{
throw(256);
}
else
{
if (temp == -1)
{
break;
}
else if (temp >= 0 && temp <= 10)
{
if (inventory.stockChecker(temp) == 1)
{
userChoice.push_back(temp);
}
}
else
{
throw(1);
}
}
cout << "\n\n";
printInventory();
} while (true);
}
catch (int error)
{
cout << "Input error: " << error << endl;
cout << "Please enter a value from 0 to 10 to select an item (-1 to exit).\n";
cout << "----------------------------------------------------------------\n";
cin.clear();
cin.ignore(256, '\n');
input();
}
}
這里的問題是,一旦我們將自己傳入Register.h,我們接受用戶輸入,然后在每次輸入后呼叫printInventoryinventory 方法。但是當我們去的時候,printInventory我們不再擁有itemList庫存物件持有的資料。
這是用于澄清物件的 main.cpp:
#include"Inventory.h"
#include"Register.h"
int main()
{
inventory inv;
inv.fileOpen();
inv.fillInventory();
inv.printInventory();
cashRegister register1;
register1.input();
register1.calcTotal();
register1.printReceipt();
}
我們的物件inv包含一個 的向量item objects,其中包含資料成員price amount name。因此,當我們創建register1物件然后嘗試再次列印庫存時,我們現在有一個空向量。我將如何實作能夠列印inv物件itemList或其他資料?
編輯:還要注意我確實嘗試通過參考傳遞 inv 物件,然后使用該物件呼叫方法。它確實有效,但感覺非常混亂。
uj5u.com熱心網友回復:
如果inv要從cashRegister物件訪問資料;而不是inv每次使用它的資料時都將物件作為參考傳遞,您可能希望在cashRegister類中保存一個指標。inventory類將具有用于操作和訪問其資料的成員函式。因此,您將能夠cashRegister從多個inventory物件訪問相同的物件,輕松地對cashRegister. 使用這種方法,您只需要使用指向類cashRegister的指標來初始化您的inventory類。
class inventory
{
public:
void printList();
void changeData();
...
};
class cashRegister
{
private:
inventory* inv;
public:
cashRegister(inventory *inv)
:
inv(inv)
{}
void printInventory()
{
inv->printList();
}
...
};
int main()
{
inventory inv;
inv.fileOpen();
inv.fillInventory();
inv.printInventory();
cashRegister register1(&inv);
cashRegister register2(&inv);
register1.input();
register1.calcTotal();
register1.printReceipt();
register1.printInventory();
register2.printInventory();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/532110.html
標籤:C 班级目的遗产标题
上一篇:在python中呼叫物件的方法時出現奇怪的問題-'self'指向錯誤的物件?
下一篇:可觀察集合型別的繼承
