在头文件中定义const对象

Define const object in a header file

本文关键字:const 对象 定义 文件      更新时间:2023-10-16

我有一个关于c++中的const关键字的问题。我有以下类:

Foot.h

class Foot
{
public:
   Foot (bool isRightFoot);
   const Vector internFootAxis;
   const Vector externFootAxis;
   bool isRightFoot;
private:
   Body* body;
}

其中Vector是实现基本R^3向量运算的类。internFootAxis表示从脚的中心(表示为Body对象-这是一个表示物理对象的类)到大脚趾的向量。externFootAxis表示从脚中心到小脚趾的矢量。

我希望internFootAxis和externFootAxis的初始值为const(因为我在图形显示主循环的每次迭代中应用操作符来改变向量的内部状态)。不幸的是,internFootAxis(t=0)和externFootAxis(t=0)的值取决于我是考虑左脚还是右脚,因此我需要在foot的构造函数中声明它们的值,而不是在类之外。

技术上讲,我想做以下操作

Foot.cpp

Foot::Foot(bool isRightFoot)
{
body = new Body();
     if (isRightFoot)
     {
         internFootAxis(1,1,0);
         externFootAxis(1,-1,0);
     }
     else
     {
         internFootAxis(1,-1,0);
         externFootAxis(1,1,0);
     }
}

有简单的方法吗?非常感谢你的帮助

v .

使用初始化器列表:

Foot::Foot(bool isRightFoot)
  : internFootAxis( 1, isRightFoot ? 1 : -1, 0)
  , externFootAxis( 1, isRightFoot ? -1 : 1, 0)
{
    body = new Body();
}