PeteMcGreete the IIII PeteMcGreete the IIII - 5 months ago 14
C++ Question

Is it possible for objects to be parameters in functions?

I have written a snippet that tries to use an object from a class as a function parameter, and I keep getting the error

In function 'int main()':
75:23: error: expected primary-expression before 'test'
75:35: error: expected primary-expression before 'Knight'


I am not sure how to fix this, as I am quite new to C++.

Some example code is down below:

// Example program
#include <iostream>
#include <string>


using namespace std;

//player class
class Player {

public:
//variable declaration
string name;
string classType;
int strength, perception, endurance, charisma, intelligence, agility, luck;
int id, cubes; // currency etc.
bool authority;
int inventory[20] = {};
int health = 100 + ((strength * endurance) * 2);
//sub stat functions
double getPick() {
return ((intelligence + luck) * (agility / 4)) * .01;
}
double getSneak() {
return (25 + (agility * 5)) * 0.01;
}
double getIntimidation() {
return (charisma * 10) * 0.01;
}
double getBarter() {
return getIntimidation();
}
double getScience() {
return ((intelligence * 5) / 3);
}
};

//enemys
class enemy {
public:
//var declaration
string name;
int HP;
double AC; //armor class ablity to resist hits
int DT; //dice used to attack
int eid; //id for enemys (enemy id)
int gear[2] = {}; //gear
//is the enemy alive?
int alive() {
if (HP <= 0) cout << "\nThe " << name << " is dead! ";
return false;
}
};

//fight an enemy (option 1)
int fightEnemy(Player player1, enemy enemy1) {
cout << "\n" << player1.name << " and a " << enemy1.name << "\n";
return 0;
}

int main() {

//test
Player test;
test.name = "test";
test.classType = "test";
test.strength = 3;
test.perception = 3;
test.endurance = 6;
test.charisma = 2;
test.intelligence = 6;
test.agility = 3;
test.luck = 5;
test.id = 1;

test.authority = true;
test.cubes = 500;

enemy Knight;
Knight.name = "Knight";
Knight.HP = 20;
Knight.AC = 0.2;
Knight.DT = 12;
Knight.eid = 3;
fightEnemy(Player test, enemy Knight);
return 0;
}

Answer Source

fightEnemy(Player test, enemy Knight);

Syntax is wrong here. You just pass the variables to the function, you are essentially declaring them again.

It should be

fightEnemy(test, Knight);