上次使用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;
}
};
uj5u.com熱心網友回復:
我可能有解決方案,但我不確定。
向量2.h
struct Vector2 {
static const Vector2 Zero;
static const Vector2 One;
float x {}, y {};
}
向量2.cpp
#include "Vector2.h"
const Vector2 Vector2::Zero = Vector2 {0, 0};
const Vector2 Vector2::One = Vector2 {1, 1};
uj5u.com熱心網友回復:
首先,使用最新版本的 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 結構的“全域”實體,您可以static像在 C# 中一樣使用C 中的關鍵字:
struct Vector2 {
float x{}, y{};
static const Vector2 Zero;
};
與C 相反,你不能直接在類中指定常量的值(如果你嘗試會incomplete type報錯,因為在編譯器遇到常量的時候,類定義還沒有完成);您需要在類之外的某處“定義”常量:
const Vector2 Vector2::Zero{};
雖然上述內容struct Vector2 ...通常位于 .h 檔案中的某個位置以被多個其他檔案包含,但定義應進入 .cpp 檔案,而不是在標題中,否則您將獲得多個定義的符號錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386142.html
