【发布时间】:2012-08-15 09:02:10
【问题描述】:
我有一个包含const 成员的类,一个构造函数调用另一个填充了额外值的构造函数。通常我可以为此使用冒号初始化程序,但函数很复杂(printf/sprintf- like) 并要求我在堆栈上使用一个变量,因此我必须在构造函数的主体中执行此操作,并将 *this 分配给新对象。但是这当然是无效的,因为我的成员变量是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 是因为我希望它们是公共的,但不是可变的。
是否有一些规范的方法可以在不使用可怕的演员表和强制覆盖成员的constness 的情况下解决这个问题?这里最好的解决方案是什么?
【问题讨论】:
标签: c++ constructor constants