如何创建一个为常量结构参数赋值的结构构造函数?
How to create a struct constructor which assigns values to constant struct parameters?
我正在尝试创建一个结构(或 class,无关紧要),其构造函数将值分配给结构的常量参数。也就是说,我不想在创建 Point 对象后更改它的任何变量。
下面的代码显然不起作用,因为构造函数试图改变常量的值。
struct point
{
const int x;
const int y;
point(int _x = 0, int _y = 0)
{
x = _x;
y = _y;
}
};
point myPoint = point(5, 10);
std::cout << myPoint.x << myPoint.y << std::endl;
struct point
{
const int x;
const int y;
point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
};
我正在尝试创建一个结构(或 class,无关紧要),其构造函数将值分配给结构的常量参数。也就是说,我不想在创建 Point 对象后更改它的任何变量。
下面的代码显然不起作用,因为构造函数试图改变常量的值。
struct point
{
const int x;
const int y;
point(int _x = 0, int _y = 0)
{
x = _x;
y = _y;
}
};
point myPoint = point(5, 10);
std::cout << myPoint.x << myPoint.y << std::endl;
struct point
{
const int x;
const int y;
point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
};