为什么模板类中的对象无法返回值?

时间:2018-11-02 19:44:24

标签: c++

template <class type , int maxSize> class queue {

private: 

    type q[maxSize]; 
    int sloc, rloc; 

public: 

    queue(); //default constructor
    void put_new_element(type element); 
    type get_element(); 
};


template <class type , int maxSize> queue<type, maxSize>::queue()
{

    sloc = rloc = 0; 

}



template <class type , int maxSize> 
void queue<type,maxSize>::put_new_element(type element)
{

    if (sloc == maxSize) 
    {
        cout << "Q is full";
        return;
    }
    else
    {
        ++sloc;
        q[sloc] = element;
    }

}


template <class type , int maxSize>
type queue<type, maxSize>::get_element()
{

    if (sloc == rloc) 
    {
        cout << "Q underflow" << endl ;
        return 0;
    }
    else
    {
        //q[1] - q[100]
        ++rloc;
        ***return q[rloc];*** 
    }
}

int main()
{

    queue<int, 2> iq;

    iq.put_new_element(1);
    iq.put_new_element(3);
    //iq.put_new_element(5); //error q is full  

    cout << "int Q:" << endl;
    cout << iq.get_element() << endl; //1
    cout << iq.get_element() << endl; //3
    //cout << iq.get_element() << endl; //error q underflow

    queue<double, 3> dp;
    dp.put_new_element(1.3);
    dp.put_new_element(3.2);
    dp.put_new_element(5.3);    
    //dp->put_new_element(5); //error q is full


    cout << "double Q:" << endl;
    cout << dp.get_element() << endl; //1.1
    cout << dp.get_element() << endl; //3.2
    cout << dp.get_element() << endl; //5.3
    //cout << dp.get_element() << endl; //error q underflow

}
  

main()(关于int队列)的第一部分在我   程序进入第二部分,双q的所有设置元素都可以。   但是当它调用return函数时会抛出(读取访问冲突   这是0x23B9246)。有人可以向我解释为什么会这样吗?   (这是我学习C ++的头几个月,语言可爱:D <3)

3 个答案:

答案 0 :(得分:1)

在增量if (sloc == maxSize)之前先放入++sloc;检查会使它无用,因此可能仍会超出范围。您到处都有这个问题。您至少应该在访问数组之前放下assert,以更快地捕获此类错误。

答案 1 :(得分:1)

我相信您的错误是在put函数中。在写入该阵列位置之前,请向该位置添加一个。好像您跳过了索引0并覆盖了数组的结尾。

由于数组布局和对齐方式的奇异性,您有时会避免这样做。然后大小发生变化,您就无法摆脱它。

答案 2 :(得分:0)

template <class type , int maxSize>
void queue<type, maxSize>::put_new_element(type element)
{
    if (sloc == maxSize) 
    {
        cout << "Q is full" << endl;
        return;
    }
    else
    {
        cout << "element seted ok" << endl;
        q[sloc] = element;
        sloc++;
    }
}

template <class type , int maxSize>
type queue<type, maxSize>::get_element()
{
    if (sloc == rloc) //dhladh exoun vgei osa stoixeia mphkan
    {
        cout << "Q underflow ";
        return 0;
    }
    else
    {

        return q[rloc++];

    }
}

我成功了。我在书上检查了++可以做得更仔细。