我正在为数据存储创建一个新的 Stack
类,它使用我的 Array
类作为数据成员。我仍在设置构造函数并且在使用赋值运算符时遇到问题。
当我调用我的赋值运算符时,它会持续调用,直到我手动取消该程序。
你能帮我找出错误吗?
如有必要,我可以为 Array
类提供代码,但我认为错误应该包含在下面的某处。
相关代码如下:
堆栈 header 代码:
#ifndef STACK_HPP
#define STACK_HPP
#include "Array_H.hpp"
namespace CLARK{
namespace Containers{
template <class Type=T> class Stack
{
private:
int m_current;
Array<Type> m_array;
public:
// constructors and destructors:
Stack(); // default constructor
// ...
~Stack(); // destructor
// ...
// modifiers:
// overloaded operator functions:
Stack<Type>& operator = (const Stack<Type>& source); // assignment operator
};
}
}
#ifndef STACK_CPP
#include "Stack.cpp"
#endif
#endif
堆栈源代码:
#ifndef STACK_CPP
#define STACK_CPP
#include "Stack_H.hpp"
namespace CLARK{
namespace Containers{
// constructors and destructors:
template <class Type>
Stack<Type>::Stack() : m_array(Array<Type>()) , m_current(0)
{ // default constructor
cout << "Stack constructor call (default)" << endl;
}
// ...
template <class Type>
Stack<Type>::~Stack()
{ // destructor
cout << "Stack destructor call" << endl;
}
// ...
// modifiers:
// overloaded operator functions:
template <class Type>
Stack<Type>& Stack<Type>::operator = (const Stack<Type>& source)
{// assignment operator
cout << "Stack assignment operator call" << endl;
if (this == &source)
return *this;
this->Stack<Type>::operator = (source);
m_current = source.m_current;
m_array = source.m_array;
return *this;
}
}
}
#endif STACK_CPP
测试代码:
#include "Point_H.hpp"
#include "Line_H.hpp"
#include "Circle_H.hpp"
#include "Array_H.hpp"
#include "NumericArray_H.hpp"
#include "Stack_H.hpp"
#include "PointArray_H.hpp"
#include "ArrayException_H.hpp"
#include "OutOfBoundsException_H.hpp"
using namespace CLARK::Containers;
using namespace CLARK::CAD;
int main()
{
try
{
Stack<int> testStack; // test default constructor
Stack<int> testStack2;
testStack2 = testStack; // test assignment operator
return 0;
} catch(ArrayException& err) {
cout << err.GetMessage() << endl;
}
}
输出如下:
Array constructor call (default)
Stack constructor call (default)
Array constructor call
Stack constructor call
Array constructor call (default)
Stack constructor call (default)
Stack assignment operator call
Stack assignment operator call
Stack assignment operator call
Stack assignment operator call
Stack assignment operator call
Stack assignment operator call
Stack assignment operator call [repeats infinitely, until I cancel it]
谢谢。
最佳答案
调用Stack<T>::operator=(source)
调用您正在实现的运营商。所以你最终得到了无限的回避。看起来有点像您想调用基类的赋值运算符,但是您的 Stack
类模板没有基类。
由于我注意到您检查了自赋值,请注意执行自赋值检查的赋值运算符要么进行了不必要的检查,要么不是异常安全的。
关于c++ - 堆栈类中的赋值运算符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12655986/