简体   繁体   English

模板类副本构造函数

[英]Template class copy constructor

I want to write copy constructor for a template class. 我想为模板类编写副本构造函数。 I have this class: 我有这个课:

template<int C>
class Word {
    array<int, C> bitCells; //init with zeros
    int size;

public:
    //constructor fill with zeros
    Word<C>() {
        //bitCells = new array<int,C>;
        for (int i = 0; i < C; i++) {
            bitCells[i] = 0;
        }
        size = C;
    }
    Word<C>(const Word<C>& copyObg) {
        size=copyObg.getSize();
        bitCells=copyObg.bitCells;
    }
}

I have errors with the copy constructor, on the line of intilizeing the size, I get: "Multiple markers at this line - passing 'const Word<16>' as 'this' argument of 'int Word::getSize() [with int C = 16]' discards qualifiers [- fpermissive] - Invalid arguments ' Candidates are: int getSize() '" 我在复制构造函数时出现错误,在利用大小的那一行上,我得到:“这行有多个标记-将'const Word <16>'作为'int Word :: getSize()的'this'参数传递int C = 16]'丢弃限定符[-fpermissive]-无效参数'候选者是:int getSize()'“

what is wrong with this ? 这有什么问题? thank you 谢谢

I'd write the class like this: 我将这样编写类:

template <std::size_t N>
class Word
{
    std::array<int, N> bit_cells_;

public:
    static constexpr std::size_t size = N;

    Word() : bit_cells_{} {}

    // public functions
};

Note: 注意:

  • No need for a dynamic size, since it's part of the type. 不需要动态尺寸,因为它是类型的一部分。

  • No need for special member functions, since the implicitly defined ones are fine. 不需要特殊的成员函数,因为隐式定义的成员函数很好。

  • Initialize the member array to zero via the constructor-initializer-list. 通过构造函数初始化列表将成员数组初始化为零。

  • Template parameter is unsigned, since it represents a count. 模板参数是无符号的,因为它代表计数。

What's wrong is that your getSize() is not declared const . 出问题的是,您的getSize()没有声明为const Make it so: 做到这一点:

int getSize() const { return size; }

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

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