[英]Define const object in a header file
I have a question concerning the const keyword in C++. 我有一个关于C ++中const关键字的问题。 I have the following class:
我有以下课程:
Foot.h Foot.h
class Foot
{
public:
Foot (bool isRightFoot);
const Vector internFootAxis;
const Vector externFootAxis;
bool isRightFoot;
private:
Body* body;
}
Where Vector is a class implementing basic R^3 vector operations. 其中Vector是实现基本R ^ 3矢量操作的类。 internFootAxis denotes the vector which goes from the center of the foot (represented as a Body object - this is a class representing a physical object) to the big toe.
internFootAxis表示从脚的中心(表示为Body对象-这是代表物理对象的类)到大脚趾的向量。 externFootAxis denotes the vector which goes from the center of the foot to the little toe.
externFootAxis表示从脚的中心到小脚趾的向量。
I want the initial value of internFootAxis and externFootAxis to be const (because I am applying operators at each iteration in the graphical display main loop to those vectors which change the inner state of the vector). 我希望将internFootAxis和externFootAxis的初始值设置为const(因为我在图形显示主循环的每次迭代中将运算符应用于那些更改矢量内部状态的矢量)。 Unfortunately, the values of internFootAxis(t=0) and externFootAxis(t=0) depends if I am considering the left or right foot, therefore I need to declare their values inside the constructor of Foot and not outside the class.
不幸的是,internFootAxis(t = 0)和externFootAxis(t = 0)的值取决于我在考虑左脚还是右脚,因此我需要在Foot的构造函数中而不是在类外部声明它们的值。
Technically I want to do the following 从技术上讲,我想执行以下操作
Foot.cpp 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);
}
}
Is there a simple way to do that ? 有没有简单的方法可以做到这一点? Thanks a lot for your help
非常感谢你的帮助
V. V.
Use initializer lists: 使用初始化列表:
Foot::Foot(bool isRightFoot)
: internFootAxis( 1, isRightFoot ? 1 : -1, 0)
, externFootAxis( 1, isRightFoot ? -1 : 1, 0)
{
body = new Body();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.