简体   繁体   English

如何使用复制构造函数复制常量变量?

[英]How do you use a copy constructor to copy over constant variables?

My class has the following private variables, including a const static one, as you can see: 您可以看到,我的类具有以下私有变量,其中包括const静态变量:

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;

I'm new to using copy constructors and I can't figure out how to write one. 我是使用复制构造函数的新手,但我不知道该怎么写。 Here's my attempt: 这是我的尝试:

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; 
}

The compiler says: 编译器说:

error: assignment of read-only variable 'BitPack::_USI_BITS' 错误:分配只读变量'BitPack :: __ USI_BITS'

Please disabuse me of my foolish ways. 请让我对我的愚蠢行为不屑一顾。

Constructors, including the copy constructors, need to set instance members , ie the ones that are not static . 构造函数(包括复制构造函数)需要设置实例成员 ,即非static Static members are shared by all instances, and therefore must be initialized outside of any constructors. 静态成员由所有实例共享,因此必须在任何构造函数之外进行初始化。

In your case, you need to remove the 对于您的情况,您需要删除

_USI_BITS = other._USI_BITS;

line: the two sides refer to the same static member, so the assignment has no effect. line:两侧引用相同的static成员,因此赋值无效。

The rest of your copy constructor is fine. 复制构造函数的其余部分都很好。 Note that since your copy constructor allocates resources, the rule of three suggests that you should add a custom assignment operator, and a custom destructor: 注意,由于复制构造函数分配资源,因此三个规则建议您应该添加一个自定义赋值运算符和一个自定义析构函数:

BitPack& operator=(const BitPack& other) {
    ...
}
~BitPack() {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM