gpt4 book ai didi

c++ - 模板复制构造函数出错

转载 作者:行者123 更新时间:2023-11-28 00:16:35 26 4
gpt4 key购买 nike

我尝试为列表创建复制构造函数。该列表将所有变量作为私有(private)成员。模板中的构造函数有什么特别之处,所以这不起作用吗?

我收到这些错误:

   1>          consoleapplication1\consoleapplication1\circulardoubledirectedlist.h(52) : while compiling class template member function 'CircularDoubleDirectedList<int>::CircularDoubleDirectedList(const CircularDoubleDirectedList<int> &)'
1> consoleapplication1\consoleapplication1\testdeepcopyingoflist.cpp(25) : see reference to function template instantiation 'CircularDoubleDirectedList<int>::CircularDoubleDirectedList(const CircularDoubleDirectedList<int> &)' being compiled
1> consoleapplication1\consoleapplication1\testdeepcopyingoflist.cpp(24) : see reference to class template instantiation 'CircularDoubleDirectedList<int>' being compiled
1>consoleapplication1\consoleapplication1\circulardoubledirectedlist.h(57): error C2039: 'dir' : is not a member of 'CircularDoubleDirectedList<int>'
1>consoleapplication1\consoleapplication1\circulardoubledirectedlist.h(62): error C2662: 'void CircularDoubleDirectedList<int>::changeDirection(void)' : cannot convert 'this' pointer from 'const CircularDoubleDirectedList<int>' to 'CircularDoubleDirectedList<int> &'
1> Conversion loses qualifiers
1>consoleapplication1\consoleapplication1\circulardoubledirectedlist.h(68): error C2662: 'void CircularDoubleDirectedList<int>::moveCurrent(void)' : cannot convert 'this' pointer from 'const CircularDoubleDirectedList<int>' to 'CircularDoubleDirectedList<int> &'
1> Conversion loses qualifiers
1>consoleapplication1\consoleapplication1\circulardoubledirectedlist.h(71): error C2662: 'void CircularDoubleDirectedList<int>::changeDirection(void)' : cannot convert 'this' pointer from 'const CircularDoubleDirectedList<int>' to 'CircularDoubleDirectedList<int> &'
1> Conversion loses qualifiers

我的代码:

template <typename T>
CircularDoubleDirectedList<T>::CircularDoubleDirectedList(const CircularDoubleDirectedList<T>& other){

bool changeDir;

if (other.getCurrentDirection == ICircularDoubleDirectedList::FORWARD){
changeDir = false;
}
else{
changeDir = true;
other.changeDirection();
}

int size = other.size();
for (int i = 0; i < size; i++){
this->addAtCurrent(other.getElementAtCurrent());
other.moveCurrent();
}
if (changeDir){
other.changeDirection();
}
this->currentDirection = other.getCurrentDirection();

}

最佳答案

您的复制构造函数(正确地)有一个 const 引用参数。但是,看起来您正试图在参数上调用非 const 成员:

other.changeDirection(); // this looks like a non-const operation
....

other.moveCurrent(); // this looks like a non-const operation

等复制构造函数修改从 复制的东西没有多大意义,但如果你真的需要它,那么你需要参数是非 const 引用.

或者,如果这些成员函数不修改对象,则将它们设为const

请注意,这与模板无关。

关于c++ - 模板复制构造函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com