在同一个方法中传递一个成员变量作为参数class
Passing a member variable as a parameter in a method of the same class
我正在用 Unreal Engine 开发游戏,我有一个 class 代表我可以在游戏关卡中移动的东西(棋子)。我正在使用球坐标来移动它。
此 class 有一种方法可以将其球坐标转换为笛卡尔位置,因为虚幻引擎使用笛卡尔位置将 pawn 放置在关卡中。
一块class是:
struct SphericalCoordinates
{
float Radius;
float Azimuth;
float Zenit;
};
class MyClass
{
public:
// Convert a spherical coordiantes to cartesian coordiantes.
FVector SphericalToCartesian(SphericalCoordinates Spherical) const;
private:
SphericalCoordinates SphereCoors;
}
私有成员 SphericalCoordinates SphereCoors
是我要作为参数传递给方法 SphericalToCartesian
的成员。换句话说,在同一个 class、MyClass
中,我将这样称呼它:
SphericalToCartesian(SphereCoors);
我使用成员变量SphereCoors
来存储class的球面坐标,而不是每次需要时都计算它。
在相同的方法中将成员变量作为参数传递是个好主意吗class?
当然,我想我可以把这个方法移到另一个class,因为它只做坐标变换,但我认为这是一个很好的问题,问它传递一个成员变量是否是一个好的设计作为相同 class.
方法中的参数
对于您的具体问题“在相同 class 的方法中将成员变量作为参数传递是个好主意吗?” - 不需要传递成员变量,因为成员函数已经可以访问这些变量了。
但是您还需要了解以下内容,因为这更像是一种实现问题的方法。
如果你的MyClass
只负责一个游戏对象(pawn),那么一个非常generic
的操作converting spherical to Cartesian co-ordinates 必须 而不是 在 class 中实现。
更喜欢编写一个实用程序 class 来执行这些通用操作 [单位转换等]。您可以创建这样一个 class 并在 class.
中实现 SphericalToCartesian
函数
然后 MyClass 可以调用该实用程序 class' 函数并传递它的成员 SphereCoors
。像这样,
class Utility
{
public static void SphericalToCartesian(SphericalCoordinates sphereCoOrds)
{
//do your conversion here
//you can return cartesian co-ords OR
//change the input argument's values, upto you
}
}
在你的 myClass 中消费
Utility.SphericalToCartesian(SphereCoors);
我正在用 Unreal Engine 开发游戏,我有一个 class 代表我可以在游戏关卡中移动的东西(棋子)。我正在使用球坐标来移动它。
此 class 有一种方法可以将其球坐标转换为笛卡尔位置,因为虚幻引擎使用笛卡尔位置将 pawn 放置在关卡中。
一块class是:
struct SphericalCoordinates
{
float Radius;
float Azimuth;
float Zenit;
};
class MyClass
{
public:
// Convert a spherical coordiantes to cartesian coordiantes.
FVector SphericalToCartesian(SphericalCoordinates Spherical) const;
private:
SphericalCoordinates SphereCoors;
}
私有成员 SphericalCoordinates SphereCoors
是我要作为参数传递给方法 SphericalToCartesian
的成员。换句话说,在同一个 class、MyClass
中,我将这样称呼它:
SphericalToCartesian(SphereCoors);
我使用成员变量SphereCoors
来存储class的球面坐标,而不是每次需要时都计算它。
在相同的方法中将成员变量作为参数传递是个好主意吗class?
当然,我想我可以把这个方法移到另一个class,因为它只做坐标变换,但我认为这是一个很好的问题,问它传递一个成员变量是否是一个好的设计作为相同 class.
方法中的参数对于您的具体问题“在相同 class 的方法中将成员变量作为参数传递是个好主意吗?” - 不需要传递成员变量,因为成员函数已经可以访问这些变量了。
但是您还需要了解以下内容,因为这更像是一种实现问题的方法。
如果你的MyClass
只负责一个游戏对象(pawn),那么一个非常generic
的操作converting spherical to Cartesian co-ordinates 必须 而不是 在 class 中实现。
更喜欢编写一个实用程序 class 来执行这些通用操作 [单位转换等]。您可以创建这样一个 class 并在 class.
SphericalToCartesian
函数
然后 MyClass 可以调用该实用程序 class' 函数并传递它的成员 SphereCoors
。像这样,
class Utility
{
public static void SphericalToCartesian(SphericalCoordinates sphereCoOrds)
{
//do your conversion here
//you can return cartesian co-ords OR
//change the input argument's values, upto you
}
}
在你的 myClass 中消费
Utility.SphericalToCartesian(SphereCoors);