类模板 重载运算符 易错
在類模板中定義重載運算符模板函數,易錯地方如下
例
錯誤(1)
#include <iostream>
using namespace std;
template <typename T>
class a
{
public:
a(T X,T Y)
{
x=X;
y=Y;
}
a operator ++();
void display()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
private:
T x,y;
};
template <typename T> a a<T>::operator++()
{
x++;
y++;
return *this;
}
int main()
{
a<int>point(534,54);
++point;
point.display();
return 0;
}
如上程序出現錯誤、~ ?
正確:
(1)
#include <iostream>
using namespace std;
template <typename T>
class a
{
public:
a(T X,T Y)
{
x=X;
y=Y;
}
a operator ++()
{
x++;
y++;
return *this;
}
void display()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
private:
T x,y;
};
int main()
{
a<int>point(534,54);
++point;
point.display();
return 0;
}
正確
(2)
#include <iostream>
using namespace std;
template <typename T>
class a
{
public:
a(T X,T Y)
{
x=X;
y=Y;
}
a <T> operator ++();
void display();
T x,y;
};
template<typename T> a<T> a<T>::operator++()
{
x++;
y++;
return *this;
}
template<typename T> void a<T>::display()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
int main()
{
a<int>point(53,54);
++point;
point.display();
return 0;
}
轉載于:https://www.cnblogs.com/sw-dream/archive/2012/06/06/2538874.html
總結
以上是生活随笔為你收集整理的类模板 重载运算符 易错的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: U8 种子ID表 及相关 存储过程
- 下一篇: 奥数解答