我是从C#转向C++而const-correctness对我来说还是新手.在C#中我可以声明这样的属性:
class Type
{
public readonly int x;
public Type(int y)
{
x = y;
}
}
Run Code Online (Sandbox Code Playgroud)
这将确保仅在初始化期间设置x.我想在C++中做类似的事情.我能想出的最好的是:
class Type
{
private:
int _x;
public:
Type(int y) { _x = y; }
int get_x() { return _x; }
};
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?更好的是:我可以使用结构吗?我想到的类型实际上只是一个数据集合,没有逻辑,所以如果我能保证只在初始化期间设置它的值,结构会更好.
有一个 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;
};
Run Code Online (Sandbox Code Playgroud)
请注意,您需要在构造函数初始化列表中初始化常量.您还可以在构造函数体中初始化其他变量.
关于你的第二个问题,是的,你可以这样做:
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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3815 次 |
| 最近记录: |