2

我知道如果我不定义复制构造函数或构造函数,C++ 自动定义它
并且我知道浅拷贝和深拷贝
但是在下面的代码中我有一个似乎与复制构造函数有关的错误

#include<iostream>
#include <vector>
using namespace std;

template<class T>
class Stack
{
    private:
        vector<T> stack;

    public:
    vector<T> returnStack()
    {
        return stack;
    }

        vector<T> returnStack() const
    {
            return stack;
    }

    void Push(T item)
    {
        stack.insert(stack.begin()+stack.size(),item);
    }

    friend Stack operator+(const Stack &one,const Stack &other);
};

template<class T>
Stack<T>  operator+(const Stack<T> &one,const Stack<T> &other)
{
    Stack<T> newStack;
    for (typename vector<T>::size_type i = 0; i < one.returnStack().size(); i++)
    {
        newStack.Push(one.returnStack()[i]);
    }
    for (typename vector<T>::size_type i = 0; i < other.returnStack().size(); i++)
    {
        newStack.Push(other.returnStack()[i]);
    }
    return newStack;
}

int main()
{
    Stack <int > a;
    Stack <int > b;
    a.Push(1);
    a.Push(2);
    b.Push(3);
    b.Push(4);
    Stack <int> c=a+b ;//have a bug
    return 0;
}

上面的代码realese下面的错误
undefined reference to operator+(Stack<int> const&, Stack<int> const&)'

我花了很多时间调试它,但我累了。你能帮我吗?

4

2 回答 2

2

Friend declarations are strange, and even stranger in templates.

This fixes it:

// forward declarations required

template<class T>
class Stack;

template<class T>
Stack<T>  operator+(const Stack<T> &one,const Stack<T> &other);

template<class T>
class Stack
{
    private:
        vector<T> stack;

    public:
    vector<T> returnStack()
    {
        return stack;
    }

        vector<T> returnStack() const
    {
            return stack;
    }

    void Push(T item)
    {
        stack.insert(stack.begin()+stack.size(),item);
    }

    friend Stack operator+<>(const Stack &one,const Stack &other);
    //                    ^^ brackets required
};

template<class T>
Stack<T>  operator+(const Stack<T> &one,const Stack<T> &other)
{

    Stack<T> newStack;
    return newStack;

}

To be honest I'm not sure why this is required, but hey, it works.

Alternatively you can define the friend function in-class:

template<class T>
class Stack
{
    private:
        vector<T> stack;

    public:
    vector<T> returnStack()
    {
        return stack;
    }

        vector<T> returnStack() const
    {
            return stack;
    }

    void Push(T item)
    {
        stack.insert(stack.begin()+stack.size(),item);
    }

    friend Stack operator+(const Stack &one,const Stack &other) {
        return Stack();
    }
};
于 2013-04-11T08:18:44.413 回答
1

简短的回答。将朋友声明更改为

friend Stack operator+<>(const Stack &one,const Stack &other);

完整的解释在这里 - http://www.parashift.com/c++-faq/template-friends.html

于 2013-04-11T08:22:35.437 回答