【问题标题】:Overload assignment(=) operator in Pair Template [duplicate]对模板中的重载赋值(=)运算符[重复]
【发布时间】:2017-12-06 17:56:28
【问题描述】:

大家好,我正在尝试实现 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 对象。

谁能帮我解决我做错的地方?

【问题讨论】:

  • T1/T2 是什么?它们是未声明的。
  • 你必须返回*this
  • s/Pair&lt;T1, T2&gt; operator = (const Pair&lt;T1, T2&gt;&amp; otherPair)/Pair&lt;T1, T2&gt;&amp; operator = (const Pair&lt;T1, T2&gt;&amp; otherPair) 和 s/return this;/return *this;
  • 发布准确的错误信息,以便未来的读者更容易找到您的问题。
  • @DevendraVerma "为什么有这么多反对意见?" 1) 通常,当询问编译错误时,您会在问题中包含此类错误。 2) 或者,您也可以只阅读错误,因为它通常会准确说明问题所在。

标签: c++ templates operator-overloading


【解决方案1】:

操作符应该是这样的

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

    return *this;
}

至于错误,那么您正在尝试将指针this 转换为运算符中Pair 类型的对象。

【讨论】:

  • 为什么要返回 *this 而不是 this?并将返回类型从 Pair 更改为 Pair&/.
  • @DevendraVerma 这具有 Pair * 类型,而返回类型是 Pair。没有从指针到 Pair 类型对象的隐式转换。在 C++ 中,赋值运算符为基本类型返回对左值的引用。所以用户定义的类应该遵循这个约定。
  • 哦,我知道了。我不清楚运算符重载的基础知识。
猜你喜欢
  • 2016-01-04
  • 1970-01-01
  • 2011-08-03
  • 2014-07-06
  • 2018-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多