模板复制构造函数给出错误

时间:2015-04-26 13:06:58

标签: c++ templates

我尝试为列表创建一个复制构造函数。该列表将所有变量都作为私有成员。模板中的构造函数是否有特殊之处,这样做不起作用?

我收到这些错误:

   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();

}

2 个答案:

答案 0 :(得分:2)

您的复制构造函数(正确地)具有const引用参数。但是,您似乎试图在论证中调用非const成员:

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

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

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

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

请注意,这与模板无关。

答案 1 :(得分:1)

第一个错误似乎不是来自此代码:代码中没有使用名称dir

剩下的错误是因为你试图在other上调用非{const}成员函数,const。要么重新考虑构造函数应该做什么(因为修改它的参数会使它相当混乱),或者从参数中删除const以允许修改。