2014-10-28 37 views
-2

我想做一個變量,將持有類指針對象。保存類指針對象的值的變量?

這是我的兩個帶有構造函數值的類指針對象。

Goblin *g = new Goblin(6, 6, 3, 8, 2,1); 
Barbarian *b = new Barbarian(6, 6, 0, 12, 2, 2); 

我想創建一個變量,將舉行這樣的數據,所以我可以有一個玩家選擇他想要什麼動物是和變量會擁有這些數據,所以我可以用我的功能。

這是我想使用的函數的標題。

void battle(Creature *a, Creature *d, std::string nameA, std::string nameD); 

這裏是被稱爲在main()

battle(g, b, playerName, opponentCreature); 

值克功能,B,是我想用我的新的變量來代替的東西。 我試過使用字符串和int類型的變量,但那不起作用。有沒有人有任何想法,我可以做到這一點?

+0

這是不是很清楚你要完成什麼。現在,你有一個「哥布林」和「野蠻人」在做戰鬥,你想要發生什麼? – Chad 2014-10-28 22:28:24

+0

我想要一個可以容納地精或野蠻人值以及更多生物的變量,並且將哪個生物分配給該變量將取決於用戶選擇的內容。這樣,當戰鬥功能被調用而不是隻有地精或蠻族戰鬥時,它將基於用戶在我沒有發佈的菜單選擇中選擇的內容。 – 2014-10-28 22:42:19

+0

聽起來像是派生和虛擬功能的工作。 – EJP 2014-10-28 22:45:58

回答

0

我通過使用這兩行來得到它的工作。

Creature *personCode = 0; 

Creature *opponentCode = 0; 

下面是他們如何綁定到我的程序。

std::cout << "Choose your creature." << std::endl; 

std::cout << "\n1). Goblin." << std::endl; 
std::cout << "2). Barbarian." << std::endl; 

std::cin >> choice; 
std::cin.clear();//clear the input 
std::cin.ignore(100, '\n');//ignore 100 char or up to new line. 

switch (choice) 
{ 
    case 1:// std::cout << "Goblin" << std::endl; 
     playerCreature = "Goblin"; 
     personCode = new Goblin(6, 6, 3, 8, 2, 1); 
     break; 

    case 2:// std::cout << "Barbarian" << std::endl; 
     playerCreature = "Barbarian"; 
     personCode = new Barbarian(6, 6, 0, 12, 2, 2); 
     break; 
} 

std::cout << "Choose your opponent" << std::endl; 

std::cout << "\n1). Goblin." << std::endl; 
std::cout << "2). Barbarian." << std::endl; 

std::cin >> choice; 
std::cin.clear();//clear the input 
std::cin.ignore(100, '\n');//ignore 100 char or up to new line. 

switch (choice) 
{ 
case 1: //std::cout << "Goblin" << std::endl; 
    opponentCreature = "Goblin"; 
    opponentCode = new Goblin(6, 6, 3, 8, 2, 1); 
    break; 

case 2: //std::cout << "Barbarian" << std::endl; 
    opponentCreature = "Barbarian"; 
    opponentCode = new Barbarian(6, 6, 0, 12, 2, 2); 
    break; 
} 

這裏是現在調用的函數。

battle(personCode, opponentCode, playerName, opponentCreature);