【问题标题】:Cpp预定义结构?
【发布时间】:2022-01-21 10:59:53
【问题描述】:

我上次使用 C++ 是在上大学的时候,所以我不是很流利。

我想创建一个小游戏,因为我习惯了 C#,所以我想创建预定义的结构对象。

这里是 C# 代码供参考:

public struct Vector2 : IEquatable<Vector2>
{

  private static readonly Vector2 _zeroVector = new Vector2(0.0f, 0.0f);
  private static readonly Vector2 _unitVector = new Vector2(1f, 1f);
  private static readonly Vector2 _unitXVector = new Vector2(1f, 0.0f);
  private static readonly Vector2 _unitYVector = new Vector2(0.0f, 1f);

  [DataMember]
  public float X;
  [DataMember]
  public float Y;

  public static Vector2 Zero => Vector2._zeroVector;
  public static Vector2 One => Vector2._unitVector;
  public static Vector2 UnitX => Vector2._unitXVector;
  public static Vector2 UnitY => Vector2._unitYVector;

  public Vector2(float x, float y)
  {
    this.X = x;
    this.Y = y;
  }
}

在 C# 中,我现在可以使用此代码获取 x = 0 和 y = 0 的向量

var postion = Vector2.Zero;

有没有办法在 C++ 中创建类似的东西,还是我必须接受 c++ 的基本知识并使用这样的结构?

struct Vector2 {
    float x, y;
    Vector2(float x, float y) {
        this->x = x;
        this->y = y;
    }
};

【问题讨论】:

  • 添加static const Vector2 Zero; 对您不起作用?在类中添加static consteval Vector2 Zero();函数怎么样?
  • 天啊,好像我的大脑暂时被关闭了,。非常感谢,很抱歉问了一个愚蠢的问题

标签: c# c++ struct


【解决方案1】:

首先,使用最新版本的 C++,您可以像这样简化结构定义:

struct Vector2 {
    float x{}, y{};
};

这保证 x 和 y 用 0 初始化,您不需要显示它的单独构造函数。然后你可以像这样使用结构:

Vector2 myVec;  // .x and .y are set to 0
myVec.x = 1; myVec.y = 2;

您甚至可以使用所谓的“初始化列表”来创建一个结构,其中包含预定义的 x 和 y 值,而不是默认的 0,如下所示:

Vector2 myVec2{1,2};

关于您对 Vector2 结构的“全局”实例的需求,您可以像在 C# 中一样在 C++ 中使用 static 关键字:

struct Vector2 {
    float x{}, y{};
    static const Vector2 Zero;
    static const Vector2 Unit;
    static const Vector2 UnitX;
    static const Vector2 UnitY;
};

与 C++ 相比,你不能直接在类中指定常量的值(如果你尝试你会得到一个incomplete type 错误,因为在编译器遇到常量的时候,类定义是尚未完成);你需要在你的类之外的某个地方“定义”常量:

const Vector2 Vector2::Zero{};
const Vector2 Vector2::Unit{1.0f, 1.0f};
const Vector2 Vector2::UnitX{1.0f, 0.0f};
const Vector2 Vector2::UnitY{0.0f, 1.0f};

虽然上面的struct Vector2 ... 通常放在 .h 文件中的某个位置以被多个其他文件包含,但定义应该放在 .cpp 文件中,而不是在头文件中,否则您将得到多重定义的符号错误。

【讨论】:

  • 如果您投了反对票,请发表评论,说明答案有哪些可以改进的地方。
  • 您基本上是在推荐个人偏好。结构恕我直言中构造函数的存在或不存在不会使其“尴尬”。通过向构造函数参数添加默认值而不客观上更好(至少在 C++20 之前,但您没有解决这个问题),可以实现相同的效果。但是,您并没有真正解决问题的核心:OP想知道是否可以执行var postion = Vector2.Zero;之类的操作(就是这种情况),但是答案中没有一句话。
  • 我正要说到那个;)但是是的,我被冲昏了头脑,可能非常离题,对此感到抱歉,感谢您的详细评论!
【解决方案2】:

我可能有一个解决方案,但我不确定。

Vector2.h

struct Vector2 {
    static const Vector2 Zero;
    static const Vector2 One;
    float x {}, y {};
}

Vector2.cpp

#include "Vector2.h"

const Vector2 Vector2::Zero = Vector2 {0, 0};
const Vector2 Vector2::One = Vector2 {1, 1};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多