C++ 如何使用复制构造函数复制常量变量?
我的类有以下私有变量,包括const static变量,如您所见:C++ 如何使用复制构造函数复制常量变量?,c++,C++,我的类有以下私有变量,包括const static变量,如您所见: private: // class constant for # of bits in an unsigned short int: const static int _USI_BITS = sizeof(usi)*CHAR_BIT; usi* _booArr; int _booArrLen; int _numBoos; 我不熟悉使用复制构造函数,但我不知道如何编写一个。以下是我的
private:
// class constant for # of bits in an unsigned short int:
const static int _USI_BITS = sizeof(usi)*CHAR_BIT;
usi* _booArr;
int _booArrLen;
int _numBoos;
我不熟悉使用复制构造函数,但我不知道如何编写一个。以下是我的尝试:
BitPack::BitPack(const BitPack& other) {
_USI_BITS = other._USI_BITS;
_booArr = new usi[other._booArrLen];
for (int i = 0; i < _booArrLen; ++i)
_booArr[i] = other._booArr[i];
_booArrLen = other._booArrLen;
_numBoos = other.numBoos;
}
BitPack::BitPack(常量BitPack和其他){
_USI_位=其他。_USI_位;
_booArr=新的usi[其他];
对于(int i=0;i<\u booArrLen;++i)
_booArr[i]=其他;
_booArrLen=其他;
_numBoos=其他。numBoos;
}
编者说:
错误:分配只读变量“BitPack::\u USI\u BITS”
请把我的愚蠢行为告诉我 构造函数,包括复制构造函数,需要设置实例成员,即不是
静态的
。静态成员由所有实例共享,因此必须在任何构造函数之外初始化
在您的情况下,您需要删除
_USI_BITS = other._USI_BITS;
行:两边都指相同的静态
成员,因此赋值无效
复制构造函数的其余部分很好。请注意,由于复制构造函数分配资源,建议您添加自定义赋值运算符和自定义析构函数:
BitPack& operator=(const BitPack& other) {
...
}
~BitPack() {
...
}
const
位是一个赠品。这是不变的!所有BitPack
实例共享相同的静态数据成员\u USI\u BITS
。因此,您确定要跨实例复制它吗?\u USI\u BITS
是const
,但您正在尝试更改它。首先,如果它依赖于类的实例化,它就不应该是<代码>静态< /代码>也不<代码> const 。好,C++默认地将复制到变量的@ uSIX位初始化为“static”。不管有多少实例,它只有一个副本。你不需要复制它。把那条线拿出来。你能解释一下如何设置赋值运算符吗?我知道在使用交换算法或其他方法时有一些细微差别。@user2967799赋值类似于复制构造函数,只是不能假定当前对象为空。在您的特定情况下,这意味着您将在为其分配新数组之前调用delete[]\u booArr
。其余的代码将与复制构造函数的代码相同。