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++ 类或结构上声明只读变量


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30