如何修复结构播放器对象中的矢量位置,以便它在 Main 中与 me.position 一起使用?

How to fix Vector Position within Struct Player object so it'll work with me.position in Main?

本文关键字:中与 Main me position 一起 对象 播放器 结构 何修复 位置      更新时间:2023-10-16

我正在自学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

#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';
}

我已经尝试了 #include 和std::vector,似乎没有任何效果。

你使用向量的方式是错误的,你必须写下指定索引或push_back(..)等条目。

所以当然你可以使用一个有 3 个条目的向量来记忆 x,y 和 z,但是定义一个结构体位置以便能够在其上添加其他行为(移动等(呢?

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

我想让它<<球员<<hp <<位置

HP位置播放器的一部分,所以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 $