我有以下文件:
main.cpp
shop.hpp
player.hpp
每个代码中都包含以下代码:
main.ccp:
#include <iostream>
#include <cstdlib>
#include "shop.hpp"
using namespace std;
string *inventory= new string[3];
int invGold= 355;
int main(void){
shop store;
store.store();
}
shop.hpp:
#include <iostream>
#include <cstdlib>
using namespace std;
class shop{
public:
string shopOption;
string shopOptions[6]= {"Buy", "buy", "Sell", "sell", "Leave", "leave"};
string shopInv[3]= {"Sword", "Potion", "Arrows x 25"};
int shopInvAmount= sizeof(shopInv)/sizeof(shopInv[0]);
int shopPrices[3]= {250, 55, 70};
shop(){
cout << "Shopkeeper: We buy, we sell, what's your buisness?" << endl;
}
void store(void){
getline(cin,shopOption);
if(shopOption.compare(shopOptions[0]) == 0 || shopOption.compare(shopOptions[1]) == 0){
buy();
}
else if(shopOption.compare(shopOptions[2]) == 0 || shopOption.compare(shopOptions[3]) == 0){
sell();
}
else if(shopOption.compare(shopOptions[4]) == 0 || shopOption.compare(shopOptions[5]) == 0){
leave();
}
}
void buy(){
srand(time(0));
string buyQuotes[3]= {"What are you buyin', hon?", "Make it quick, I ain't got all day.", "Another day, another sell."};
int quotePick= rand() % sizeof(buyQuotes)/sizeof(buyQuotes[0]) - 1;
if (quotePick < 0){
quotePick= 0;
}
else if (quotePick > (sizeof(buyQuotes)/sizeof(buyQuotes))){
quotePick= sizeof(buyQuotes)/sizeof(buyQuotes);
}
cout << "TEST:" << sizeof(shopInv)/sizeof(shopInv[0]) << endl;
cout << buyQuotes[quotePick] << endl;
cout << "SHOP INVENTORY" << endl << "--------------" << endl;
cout << endl;
for (int i=0; i < sizeof(shopInv)/sizeof(shopInv[0]); i++){
cout << shopInv[i]<< ": " << shopPrices[i] << endl;
}
cout << endl << "What'll it be?:";
getline(cin,shopOption);
}
void sell(){
}
void leave(){
}
};
和player.hpp
class player{
public:
int playerHP= 18;
string playerInv[5] {};
int playerGold= 355;
};
现在,我想做的是,在角色选择他们想要购买的物品之后,以及它的数量,(尚未编程)检查组合物品的价格,并查看角色有足够的钱,如果角色购买物品,将它们添加到玩家的库存中。
但是我想保留商店使用的值,以及与不同类文件中的播放器相关的所有内容。 事情是,我不知道如何拉这样的东西。
那么,是否可以从另一个文件中的另一个类中访问一个类'变量? 如果不是,你会如何建议我解决这个问题?
答案 0 :(得分:0)
从这里开始阅读:How does the compilation/linking process work?以获取多个适合您的文件。无论您使用何种编码环境,都可以自动完成整个过程。
然后考虑制作一个项目类
class Item
{
public:
Item(string name, int price): mName(name), mPrice(price)
{
}
string getName()
{
return mName;
}
string getPrice()
{
return mPrice;
}
// other functions
private:
string mName;
int mPrice;
// other stuff
}
在商店和玩家中,保留一个项目列表
vector<Item> items;
当玩家试图购买物品时,在列表中找到它,确保玩家能够负担得起,将其从商店列表中删除并将其添加到玩家列表中。