【问题标题】:Default value for parameter of class where value is another class值是另一个类的类参数的默认值
【发布时间】:2022-01-02 09:25:03
【问题描述】:

标题可能有点混乱,但基本上我有一个“四元数”类,它有 2 个参数,第一个是 Vector3 类的另一个实例,另一个是浮点数。

Vector3 将 3 个浮点数作为参数并将它们分配给 x、y 和 z。

我想为 Quaternion 类设置默认参数,但我不确定如何以类为参数设置默认参数。

Vector3

class Vector3 {
  public:
    float x, y, z;

    Vector3(float uX, float uY, float uZ) {
      this->x = uX;
      this->y = uY;
      this->z = uZ; 
    }
};

四元数

class Quaternion {
  public:
    Vector3 axis;
    float scalar;

    Quaternion(Vector3 uAxis, float uScalar = 0) {
      axis = uAxis;
      scalar = uScalar;
    };
};

我想将uAxis 的默认参数设为Vector3,其中x、y 和z 分别设置为1, 0, 0,但我不确定如何做到这一点。

【问题讨论】:

  • 我喜欢将静态默认值添加到矢量类本身的模式。也许uprightforward。然后,您可以使用 Vector3 uAxis = Vector3::right 或您环境中的任何 x。但我相信Vector3 uAxis = Vector3(1.f, 0.f, 0.f) 也会起作用。

标签: c++ class


【解决方案1】:

我想这就是你要找的东西:

class Quaternion {
  public:
    Vector3 axis;
    float scalar;

    Quaternion(Vector3 uAxis = Vector3(1.0, 0.0, 0.0), float uScalar = 0) {
      axis = uAxis;
      scalar = uScalar;
    };
};

可以调用类的构造函数来设置默认参数。这里是对应的cpp参考default arguments

【讨论】:

  • 哇,看到解决方案后,它看起来如此明显,哈哈,伙计。
【解决方案2】:

这就是你想要的。除非您必须对参数docs 做一些事情,否则请始终使用构造函数上的初始化列表。此外,我将 uAxis 作为 const 引用传递,这对于 ADT(抽象数据类型)总是一件好事,除非您有特殊要求。

 class Quaternion 
 {
    Vector3 axis;
    float scalar;

 public:
    Quaternion(const Vector3 & uAxis = Vector3(1.0, 0.0, 0.0), float uScalar = 0) :
      axis(uAxis),
      scalar(uScalar)
    {
    }
 };

【讨论】:

    【解决方案3】:

    另一种选择是将default member initialization 用于axisQuaternion 中。这样,只需创建一个 Quaternion q{} 即可将 axis 设置为您想要的任何内容。 [Demo]

    class Quaternion {
    public:
        Vector3 axis{1.0, 0.0, 0.0};
        float scalar{};
    
        Quaternion() = default;
        ...
    };
    

    对于Quaternion(Vector3 uAxis, float uScalar) 构造函数,最好使用成员初始化列表:

    Quaternion(Vector3 uAxis, float uScalar) : axis{uAxis}, scalar{uScalar} {};
    

    另外,您可以删除Vector3 的构造函数,使Vector3 成为aggregate

    struct Vector3 {
        float x{};
        float y{};
        float z{};
    };
    
    Vector3 v{1.1, 2.2, 3.3};
    

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2018-02-27
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 2014-04-19
      • 1970-01-01
      • 2017-02-27
      相关资源
      最近更新 更多