你如何正确地初始化一个结构,它的成员是一个指向 const 值的 const 指针?
How do you correctly initialize a struct with a member that is a const pointer to a const value?
目前我正在做这样的事情:
struct foo
{
const int
*const a,
*const b,
*const c;
foo(int a, int b, int c)
: a(_a), b(_b), c(_c)
{
*_a = a;
*_b = b;
*_c = c;
}
private:
int _a[1], _b[1], _c[1];
};
但是有没有办法在不输入第二组指针的情况下做到这一点 (_a, _b, _c
)?
but is there a way to do this without putting in the second set of pointers (_a
, _b
, _c
)?
当然可以。您可以使用:
foo(int a, int b, int c)
: a(new int(a)), b(new int(b)), c(new int(c)) {}
牢记The Rule of Three并为foo
适当地实现复制构造函数、复制赋值运算符和析构函数。
目前我正在做这样的事情:
struct foo
{
const int
*const a,
*const b,
*const c;
foo(int a, int b, int c)
: a(_a), b(_b), c(_c)
{
*_a = a;
*_b = b;
*_c = c;
}
private:
int _a[1], _b[1], _c[1];
};
但是有没有办法在不输入第二组指针的情况下做到这一点 (_a, _b, _c
)?
but is there a way to do this without putting in the second set of pointers (
_a
,_b
,_c
)?
当然可以。您可以使用:
foo(int a, int b, int c)
: a(new int(a)), b(new int(b)), c(new int(c)) {}
牢记The Rule of Three并为foo
适当地实现复制构造函数、复制赋值运算符和析构函数。