在使用const成员构造对象时调用另一个构造函数 [英] Calling another constructor when constructing an object with const members
问题描述
我有一个类与 const
成员,一个构造函数调用另一个构造函数与额外的值填充。通常我可以使用冒号初始化为此,但函数是复杂的( printf
/ sprintf
-like),并要求我在堆栈上使用一个变量,在构造函数的主体中这样做,并使用assign * this
到新对象。但是当然这是无效的,因为我的成员变量是 const
。
I have a class with const
members, and one constructor which calls another constructor with extra values filled in. Normally I could use a colon initializer for this, but the function is complex (printf
/sprintf
-like) and requires me to use a variable on the stack, so I have to do this in the body of the constructor and use assign *this
to the new object. But of course this is invalid, because my member variables are const
.
class A
{
public:
A(int b) : b(b), c(0), d(0) // required because const
{
int newC = 0;
int newD = 0;
myfunc(b, &newC, &newD);
*this = A(b, newC, newD); // invalid because members are const
// "cannot define the implicit default assignment operator for 'A', because non-static const member 'b' can't use default assignment operator"
// or, sometimes,
// "error: overload resolution selected implicitly-deleted copy assignment operator"
};
A(int b, int c, int d) : b(b), c(c), d(d) { };
const int b;
const int c;
const int d;
};
A a(0);
(我没有明确删除赋值操作符。)我声明了成员const,因为我想
(I haven't explicitly deleted the assignment operator.) I declared the members const because I would like them to be public, but not mutable.
有没有一个规范的方法来解决这个问题,而不使用可怕的强制转换和强制成员的 const
ness?
Is there some canonical way of solving this problem without using scary casts and force-overriding the members' const
ness? What's the best solution here?
推荐答案
您可以添加参数类并使用C ++ 11构造函数委托或基类:
You can add a parameters class and use either C++11 constructor delegation or a base class:
struct parameters {
int b; int c; int d;
parameters(int b): b(b), c(), d() {
myfunc(b, &c, &d);
}
};
// constructor delegation
class A {
public:
A(int b): A(parameters(b)) { }
A(parameters p): b(p.b), c(p.c), d(p.d) { }
};
// base/wrapper
class ABase {
ABase(parameters p): b(p.b), c(p.c), d(p.d) { }
};
class A: public ABase {
public:
A(int b): ABase(parameters(b)) { }
};
这篇关于在使用const成员构造对象时调用另一个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!