我收到一些错误。我需要使用operator =将成员传递给 const 成员。 我不知道什么是错误,我的功能声明是:
template<class I> forceinline
void OverweightValues<I>::init(int t,
SharedArray<int>& elements0,
SharedArray<int>& weights0,
I& i) {
{..}
//both are declared as 'const SharedArray<int> elements, weights;'
//but elements0 and weights0 not is const
elements = elements0;
weights = weights0;
编译时得到错误:
In line(16): no operator "=" matches these operands operand types are: const SharedArray<int> = SharedArray<int>
In line(17): no operator "=" matches these operands operand types are: const SharedArray<int> = SharedArray<int>
我该如何解决这个问题?
答案 0 :(得分:1)
const
成员只能在创建期间设置。您需要使用构造函数初始化列表而不是两阶段构造。 (甚至构造函数体也无法分配它们)
答案 1 :(得分:0)
正如@Ben Voigt所提到的,你只能在构造函数初始化列表中初始化一个const。这是因为,当控件到达构造函数体时,编译器已使用默认构造函数创建了所有类成员。
因此,构造函数体内的成员初始化实际上会调用赋值构造函数,而对于默认构造函数不可用的常量,引用或对象,这些构造函数是无法完成的。