【问题标题】:Template class copy constructor模板类复制构造函数
【发布时间】:2016-03-22 12:20:53
【问题描述】:

我想为模板类编写复制构造函数。我有这门课:

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

我的复制构造函数有错误,在 intilize 大小的行上,我得到: “这条线上的多个标记 - 传递 'const Word' 作为 'int Word::getSize() [with int C = 16]' 的 'this' 参数丢弃限定符 [- fpermissive] - 无效参数 ' 候选者是:int getSize() '"

这有什么问题? 谢谢你

【问题讨论】:

  • 第一步:去掉构造函数名称后面的&lt;C&gt;
  • 根据错误,您的代码摘录中未包含的成员getSize() 是非const 成员:将其设为const 成员。
  • 像这样:“Word(const Word& copyObg)”?这是为什么? (仍然是同样的错误..)
  • 好像不需要自己定义拷贝构造函数;隐式定义的应该就可以了。
  • 构造函数的名字是Word,而不是Word&lt;C&gt;。您将使用 Word&lt;C&gt; 作为构造函数定义中的类名:template &lt;int C&gt; Word&lt;C&gt;::Word(Word&lt;C&gt; const&amp; copyObg) { ... }

标签: c++ templates copy-constructor


【解决方案1】:

我会这样写课程:

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

注意:

  • 不需要动态大小,因为它是类型的一部分。

  • 不需要特殊的成员函数,因为隐式定义的就可以了。

  • 通过constructor-initializer-list将成员数组初始化为零。

  • 模板参数是无符号的,因为它代表一个计数。

【讨论】:

  • 关于你的最后一点:这会产生破坏static_assert(N &gt;= 0, "Array size must be positive"); 之类的负面后果,如果Word 的模板参数不是负整数文字而是某些负数的结果,这可能会变得危险编译时计算 (Word&lt;A::size - B::size&gt;)。这与无符号函数参数的问题基本相同。
【解决方案2】:

问题是您的getSize() 没有声明为const。这样做:

int getSize() const { return size; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多