对象 X 不是结构 Y 的成员

object x is not a member of struct y

本文关键字:成员 结构 对象      更新时间:2023-10-16
#pragma once
#include "Predefined.h"
#include <string>
#include <vector>
using namespace std;
namespace Packets
{
enum { EnumLoginData, EnumPlayerData };
struct LoginData
{
    std::string username;
    std::string password;
};
struct PlayerData
{
    Predefined::Vector2 position;
};
struct MainPacket
{
    char type;
    int id;
    LoginData loginData;
    vector<PlayerData> playerData;
};
}

上面的代码是一个名为 PacketDefines.h 的单个头文件。我准备了几个结构,如您所见,我将在程序的另一部分使用它们。现在,结构 PlayerData 使用一个 Predefined::Vector2 对象,这是我在 Predefined.h 中创建的自定义结构,包含在当前头文件中。

问题是我收到此错误:

error C2146: syntax error : missing ';' before identifier 'position'

此外,这使得代码中的其他内容(依赖于此结构(会导致引发错误:

error C2039: 'position' : is not a member of 'Packets::PlayerData'

这是预定义的头文件:

#pragma once
#include <iostream>
#include <memory>
#include "PacketDefines.h"
// some other includes
using namespace std;
#define LOBBY_MAX_CONNECTIONS 5
#define MAX_DATA_SIZE 512
namespace Predefined
{
struct Vector2
{
    Vector2(float valueX = 0.0f, float valueY = 0.0f) : x(valueX), y(valueY) {}
    float x;
    float y;
};
struct Vector3
{
    Vector3(float valueX = 0.0f, float valueY = 0.0f, float valueZ = 0.0f) : x(valueX), y(valueY), z(valueZ) {}
    float x;
    float y;
    float z;
};
struct Connection
{
    int ID;
    SOCKET socket;
    Packets::PlayerData playerData;
};
struct Lobby
{
    string lobbyName;
    vector<Connection> connectionList;
};
}

我不知道发生了什么,因为据我所知,一切都是相互关联的。我希望我的问题很清楚,有人可以帮助我解决这些错误。

这是一个肤浅的概述,但你的"Predefined.h"包含两个不同的部分;第一个是你的Vector类,第二个是包含应用程序逻辑的更复杂的类。为了克服这个问题,你实际上需要三个头文件:

  • Vectors.h -> 应定义Vector2Vector3,并且不包含任何应用程序结构
  • PacketDefines.h -> 应该#include "Vectors.h",没有别的(不需要包括Predefined.h(。
  • Connection.h ->应该#include "PacketDefines.h".

超出这个问题的范围,我还建议将标题名称更改为更有意义的名称(是的,标头通常声明符号并定义结构;那又怎样?(。