首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

小弟遭遇模板友元函数的奇怪异常,真心求大神赐教

2013-01-23 
小弟遭遇模板友元函数的奇怪错误,真心求大神赐教//////////////////////////////////////////////////////

小弟遭遇模板友元函数的奇怪错误,真心求大神赐教
////////////////////////////////////////////////////////////////////////
///以下是stack.h中内容
/////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <vector>

using namespace std;

template <typename T>
class Stack {
private :
    vector<T> vect;
    friend Stack<T> operator+<>(const Stack<T> &a, const Stack<T> &b);
public :
    bool empty() const;
    void push(const T &item);
    T &top();
    void pop();
};

template <typename T>
bool Stack<T>::empty() const {
    if(vect.empty()) {
        return true;
    }
    else {
        return false;
    }
}

template <typename T>
void Stack<T>::push(const T &item) {
    vect.push_back(item);
}

template <typename T>
T &Stack<T>::top() {
    return vect.back();
}

template <typename T>
void Stack<T>::pop() {
    if(vect.empty() != true) {
        vect.pop_back();
    }
}

template <typename T>
Stack<T> operator+(const Stack<T> &a, const Stack<T> &b) {
    Stack<T> temp1, temp2;
    temp1 = a;
    temp2 = b;
    while(temp2.empty() != true) {
        temp1.push(temp2.top());
        temp2.pop();
    }
    return temp1;
}
////////////////////////////////////////////
///以下是main.cpp中内容
////////////////////////////////////////////
#include <iostream>
#include "Stack.h"

using namespace std;

int main()
{
    Stack<int> stack1;
    stack1.push(1);
    stack1.push(2);
    stack1.push(3);
    Stack<int> stack2;
    stack2.push(4);
    stack2.push(5);
    Stack<int> stack3 = stack1 + stack2;
    cout << stack3.top() <<endl;
}
小弟使用codeblocks下的gcc编译,报出奇怪错误
D:\cb\Stack\Stack.h:10: error: template-id 'operator+<>' for 'Stack<int> operator+(const Stack<int>&, const Stack<int>&)' does not match any template declaration
小弟真心搞不懂为什么说那个友原函数不匹配任何模板,请前辈指教,谢谢。
 

[解决办法]
模板友元与普通友元存在一点不同的地方,就是在友元声明处,其模板声明或定义必须可见,在Stack之前加上入下声明就可:

template <typename T>
class Stack;

template <typename T>


Stack<T> operator+(const Stack<T> &a, const Stack<T> &b);
[解决办法]

引用:
不出错是不对的。

前辈 ,你试试吧? 一个.H和一个.CPP  , windows系统,VS系列编译器

热点排行