Как исправить положение вектора в объекте Struct Player, чтобы он работал с me.position в Main? - PullRequest
0 голосов
/ 26 апреля 2019

Я учу себя C ++ 11, и это было одно из моих домашних заданий, однако векторное положение; не похоже на работу.

Я пробовал #include и std :: vector, похоже, ничего не работает.

#include <iostream>
#include <string>
using namespace std;


struct Player
{
    string name;
    int hp;
    vector position;
}; 

int main()
{
   Player me;
   me.name = "Metalogic";
   me.hp = 100;
   me.position.x = me.position.y = me.position.z = 0;

   return 0;
}

Я бы хотел за это cout << player << hp << position

Ответы [ 2 ]

0 голосов
/ 26 апреля 2019
#include <iostream>
#include <string>

struct Vector3D
{
    int x, y, z;
};

std::ostream& operator<<(std::ostream &os, Vector3D const &position)
{
    return os << '[' << position.x << ", " << position.y << ", " << position.z << ']';
}

struct Player
{
    std::string name;
    int hp;
    Vector3D position;
}; 

std::ostream& operator<<(std::ostream &os, Player const &player)
{
    return os << '\"' << player.name << "\" (" << player.hp << ") " << player.position;
}

int main()
{
    Player me{ "Metalogic", 100, {} };
    std::cout << me << '\n';

    Player you{ "Luigi", 900, { 1, 2, 3 } };
    std::cout << you << '\n';
}
0 голосов
/ 26 апреля 2019

Я пробовал #include и std :: vector, похоже, ничего не работает.

Ваш способ использовать vector неправильный, вы должнынапишите в записях, указав индекс или push_back(..) и т. д.

Так что, конечно, вы можете использовать вектор с 3 записями для запоминания x, y и z, но как насчет определения struct Position чтобы иметь возможность добавить к нему дополнительные варианты поведения ( move и т. д.)?

struct Position {
  int x;
  int y;
  int z;
}

struct Player
{
    string name;
    int hp;
    Position position;
}; 

int main()
{
   Player me;
   me.name = "Metalogic";
   me.hp = 100;
   me.position.x = me.position.y = me.position.z = 0;

   return 0;
}

Обратите внимание, что у вас также может быть конструктор по умолчанию, инициализирующий x, y и z равными 0, чтобы не требовалосьделать каждый раз

struct Position {
  Position() : x(0), y(0), z(0) {}
  int x;
  int y;
  int z;
}

struct Player
{
    string name;
    int hp;
    Position position;
}; 

int main()
{
   Player me;
   me.name = "Metalogic";
   me.hp = 100;

   return 0;
}

Я бы хотел, чтобы он сидел << player << hp << position </p>

hp и позиция является частью Player , поэтому std::cout << player достаточно

Просто добавьте operator<<

#include <iostream>
#include <string>

struct Position {
  Position() : x(0), y(0), z(0) {}

  friend std::ostream& operator<<(std::ostream& os, const Position & p) {
     os << "[" << p.x << ' ' << p.y << ' ' << p.z << ']';
     return os;
  }
  int x;
  int y;
  int z;
};

struct Player
{
    friend std::ostream& operator<<(std::ostream& os, const Player & p) {
       os << p.name << ' ' << p.hp << ' ' << p.position;
       return os;
    }
    std::string name;
    int hp;
    Position position;
}; 

int main()
{
   Player me;
   me.name = "Metalogic";
   me.hp = 100;
   me.position.x = 123; // y and z use default value 0

   std::cout << me << std::endl;
   return 0;
}

Компиляция и выполнение:

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall p.cc
pi@raspberrypi:/tmp $ ./a.out
Metalogic 100 [123 0 0]
pi@raspberrypi:/tmp $ 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...