C++ 为什么模板类中的对象不能返回值? 模板类队列{ 私人: q型[最大尺寸]; int sloc,rloc; 公众: queue();//默认构造函数 无效放置新元素(类型元素); 键入get_元素(); }; 模板队列::队列() { sloc=rloc=0; } 模板 无效队列::放置新元素(类型元素) { 如果(sloc==maxSize) { cout
putC++ 为什么模板类中的对象不能返回值? 模板类队列{ 私人: q型[最大尺寸]; int sloc,rloc; 公众: queue();//默认构造函数 无效放置新元素(类型元素); 键入get_元素(); }; 模板队列::队列() { sloc=rloc=0; } 模板 无效队列::放置新元素(类型元素) { 如果(sloc==maxSize) { cout,c++,C++,putif(sloc==maxSize)在增量之前检查++sloc;会使其无效,因此可能仍然会越界访问。您到处都有这个问题。您至少应该在访问数组之前放置assert,以更快地捕获这种类型的错误。我相信您的错误存在于put函数中。在向数组写入之前,您会在位置添加一个assert在数组位置。看起来您跳过了索引0并覆盖了数组的结尾 由于阵列布局和对齐方式的奇怪性,您有时可以侥幸逃脱。然后大小会发生变化,您无法逃脱。就是这样,bro.q[sloc];sloc++;并返回q[rloc++],非常感谢您:D
if(sloc==maxSize)
在增量之前检查++sloc;
会使其无效,因此可能仍然会越界访问。您到处都有这个问题。您至少应该在访问数组之前放置assert,以更快地捕获这种类型的错误。我相信您的错误存在于put函数中。在向数组写入之前,您会在位置添加一个assert在数组位置。看起来您跳过了索引0并覆盖了数组的结尾
由于阵列布局和对齐方式的奇怪性,您有时可以侥幸逃脱。然后大小会发生变化,您无法逃脱。就是这样,bro.q[sloc];sloc++;并返回q[rloc++],非常感谢您:D
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
}