我有一个非常简单的课程。它有一个指针成员变量。我想重载 + 运算符。但是,它不起作用!这是我的代码:
#include <iostream>
using namespace std;
template <typename T>
struct Node{
Node *next;
T data;
};
template <typename T>
class stack{
protected:
Node <T> *head;
public:
stack();
~stack();
bool push(T);
stack <T> operator+ (stack <T>);
};
template <typename T>
stack<T>::stack(){
head = NULL;
}
template <typename T>
stack <T>::~stack(){
Node <T> *temp;
while(head){
temp = head;
head = head->next;
delete temp;
}
}
template <typename T>
bool stack <T>::push(T data){
Node <T> *newElem = new Node <T>;
if (!newElem) return false;
newElem->next = head;
newElem->data = data;
head = newElem;
return true;
}
template <typename T>
stack <T> stack<T>::operator+ (stack <T> stack1){
stack <T> result;
Node <T> *temp = head;
while (temp) {
result.push(temp->data);
temp = temp->next;
}
temp = stack1.head;
while (temp) {
result.push(temp->data);
temp = temp->next;
}
return result;
}
int main(){
stack <int> myStack1, myStack2, myStack3;
myStack1.push (1);
myStack1.push (2);
myStack2.push (3);
myStack2.push (4);
myStack3 = myStack1 + myStack2; // here at runtime myStack3 is not the result of myStack1 + myStack2.
return 0;
}
你能帮我解决这个问题吗?请注意,这只是为了练习。
非常感谢。