Declaring readonly variables on a C++ class or struct(在 C++ 类或结构上声明只读变量)
问题描述
我从 C# 开始使用 C++,而 const 正确性对我来说仍然是新事物.在 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++ 类或结构上声明只读变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 类或结构上声明只读变量
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 将函数的返回值分配给引用 C++? 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
