问题描述
我从C#进入C ++,而const-correctness对我来说仍然是新事物。在C#中,我可以声明这样的属性:
I'm coming to C++ from C# and const-correctness is still new to me. In C# I could declare a property like this:
class Type
{
public readonly int x;
public Type(int y)
{
x = y;
}
}
这将确保x仅在初始化期间设置。我想在C ++中做类似的事情。我能想到的最好的方法是:
This would ensure that x was only set during initialization. I would like to do something similar in C++. The best I can come up with though is:
class Type
{
private:
int _x;
public:
Type(int y) { _x = y; }
int get_x() { return _x; }
};
是否有更好的方法?甚至更好:我可以使用结构体来做到这一点吗?我想到的类型实际上只是数据的集合,没有逻辑,因此如果我可以保证仅在初始化期间设置其值,则结构会更好。
Is there a better way to do this? Even better: Can I do this with a struct? The type I have in mind is really just a collection of data, with no logic, so a struct would be better if I could guarantee that its values are set only during initialization.
推荐答案
有一个 const
修饰符:
class Type
{
private:
const int _x;
int j;
public:
Type(int y):_x(y) { j = 5; }
int get_x() { return _x; }
// disable changing the object through assignment
Type& operator=(const Type&) = delete;
};
请注意,您需要在构造函数初始化列表中初始化常量。您还可以在构造函数主体中初始化其他变量。
Note that you need to initialize constant in the constructor initialization list. Other variables you can also initialize in the constructor body.
关于第二个问题,是的,您可以执行以下操作:
About your second question, yes, you can do something like this:
struct Type
{
const int x;
const int y;
Type(int vx, int vy): x(vx), y(vy){}
// disable changing the object through assignment
Type& operator=(const Type&) = delete;
};
这篇关于在C ++类或结构上声明只读变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!