对象是否可以作为函数中的参数?

时间:2017-05-12 04:49:37

标签: c++ class oop

我编写了一个片段,试图将类中的对象用作函数参数,并且我不断收到错误

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

我不知道如何解决这个问题,因为我对C ++很陌生。

下面是一些示例代码:

// 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;
    }

2 个答案:

答案 0 :(得分:5)

  

战斗敌人(玩家测试,敌人骑士);

这里语法错误。您只需将变量传递给函数,您基本上就是再次声明它们。

应该是

fightEnemy(test, Knight);

答案 1 :(得分:0)

fightEnemy(Player test, enemy Knight);

fightEnemy(test, Knight);

变量已经初始化。