【发布时间】: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<T1, T2> operator = (const Pair<T1, T2>& otherPair)/Pair<T1, T2>& operator = (const Pair<T1, T2>& otherPair)和 s/return this;/return *this;。 -
发布准确的错误信息,以便未来的读者更容易找到您的问题。
-
@DevendraVerma "为什么有这么多反对意见?" 1) 通常,当询问编译错误时,您会在问题中包含此类错误。 2) 或者,您也可以只阅读错误,因为它通常会准确说明问题所在。
标签: c++ templates operator-overloading