[英]In C++, how to declare a class member that can only be changed externally?
I have a class like this我有一个像这样的 class
class Foo {
public:
Matrix M;
Foo();
~Foo();
}
I want M
to be immutable inside the class (internal member functions cannot change it), but code outside the class should be able to update it without constraint, is there a way to do so?我希望M
在 class 内部是不可变的(内部成员函数无法更改它),但是 class 外部的代码应该能够不受限制地更新它,有没有办法这样做?
A little background : I'm working on an OpenGL application, where I have a Mesh
class that holds all the vertices/textures data and can Draw()
on demand.一点背景知识:我正在开发一个 OpenGL 应用程序,其中我有一个Mesh
class 保存所有顶点/纹理数据并且可以按需Draw()
。 I realized that the viewing matrix and projection matrix are global to the scene, while the model matrix M
is local to every mesh, so I declared M
as a public member of the Mesh
class, which is initialized to the identity matrix.我意识到观察矩阵和投影矩阵对于场景来说是全局的,而 model 矩阵M
对于每个网格都是局部的,所以我将M
声明为网格 class 的公共成员,该Mesh
初始化为单位矩阵。 The caller outside the class should update M
every frame to do transformations. class 之外的调用者应该每帧更新M
以进行转换。 However, I don't want it to be accidentally changed from within the class.但是,我不希望它在 class 中被意外更改。 Hope this makes sense.希望这是有道理的。
This seems to be violating the c++
principles, but I need to somehow tie M
to an instance of the class.这似乎违反了c++
原则,但我需要以某种方式将M
绑定到 class 的实例。 The Matrix
type is actually glm::mat4
btw. Matrix
类型实际上是glm::mat4
顺便说一句。
Move M
outside of Foo
, and then give Foo
a const
pointer/reference to M
, eg:将M
移到Foo
之外,然后给Foo
一个指向M
的const
指针/引用,例如:
Matrix M;
class Foo {
public:
const Matrix &Mref;
Foo() : Mref(M) {}
~Foo();
};
How about something like像这样的东西怎么样
struct Matrix {
void change() {}
};
class Foo {
public:
Matrix M;
void bar() const {
// M.change(); can't change since it's a const function.
}
Foo();
~Foo();
};
int main() {
Foo f;
f.M.change();
}
Have all operations inside Foo
within const
functions, yet expose M
itself to the outer world.将Foo
中的所有操作都包含在const
函数中,但将M
本身暴露给外部世界。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.