【发布时间】: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() '"
这有什么问题? 谢谢你
【问题讨论】:
-
第一步:去掉构造函数名称后面的
<C>。 -
根据错误,您的代码摘录中未包含的成员
getSize()是非const成员:将其设为const成员。 -
像这样:“Word(const Word
& copyObg)”?这是为什么? (仍然是同样的错误..) -
好像不需要自己定义拷贝构造函数;隐式定义的应该就可以了。
-
构造函数的名字是
Word,而不是Word<C>。您将使用Word<C>作为构造函数定义中的类名:template <int C> Word<C>::Word(Word<C> const& copyObg) { ... }。
标签: c++ templates copy-constructor