对模板中的过载分配(=)操作员



大家好,我正在尝试实现一个像模板一样实现 pair。我已经尝试过:

#include<iostream>
using namespace std;
template<class T1, class T2>
class Pair
{
    //defining two points
    public:
    T1 first;
    T2 second;
    //default constructor
    Pair():first(T1()), second(T2())
    {}
    //parametrized constructor
    Pair(T1 f, T2 s) : first(f),second(s)
    {}
    //copy constructor
    Pair(const Pair<T1,T2>& otherPair) : first(otherPair.first), second(otherPair.second)
    {}
    //overloading == operator
    bool operator == (const Pair<T1, T2>& otherPair) const
    {
        return (first == otherPair.first) && (second == otherPair.second);
    }
    //overloading = operator
    Pair<T1, T2> operator = (const Pair<T1, T2>& otherPair) 
    {
        first=otherPair.first;
        second=otherPair.second;
        return this;
    }

    int main()
    {
        Pair<int, int> p1(10,20);
        Pair<int, int> p2;
        p2 = p1;
    }

,但我在超载方法的最后一行中遇到了错误=。它不允许返回this对象。

有人可以在我做错的地方提供帮助吗?

操作员应该看起来像

//overloading = operator
Pair<T1, T2> & operator = (const Pair<T1, T2>& otherPair) 
{
    if ( this != &otherPair )
    {
        first=otherPair.first;
        second=otherPair.second;
    }
    return *this;
}

至于错误,您正在尝试将指针this转换为操作员类型Pair的对象。

最新更新