鱼C论坛

 找回密码
 立即注册
查看: 1420|回复: 2

小白求助 关于模板类的问题

[复制链接]
发表于 2020-5-8 12:16:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include "iostream"
  2. using std::endl;
  3. using std::cout;
  4. using std::cin;
  5. using std::ostream;

  6. template <typename T>
  7. class Complex
  8. {
  9. private:
  10.         T a;
  11.         T b;
  12. public:
  13.         Complex(T a, T b);
  14.         void printCom();
  15. public:
  16.         friend ostream& operator<<<T>(ostream& out, Complex& c);//问题出在这一行 模板类的友元函数 重载<<操作符 我看视频上 需要加上一个<T>  可是加上<T>后报错 是怎么回事
  17.         Complex operator+(Complex& c);
  18. };

  19. template <typename T>
  20. Complex<T>::Complex<T>(T a, T b)
  21. {
  22.         this->a = a;
  23.         this->b = b;
  24. }

  25. template <typename T>
  26. void Complex<T>::printCom()
  27. {
  28.         cout << this->a << " " << this->b << endl;
  29. }

  30. template <typename T>
  31. ostream& operator<<(ostream& out, Complex<T>& c)
  32. {
  33.         out << c.a << " " << c.b << endl;
  34.         return out;
  35. }

  36. template <typename T>
  37. Complex<T> Complex<T>::operator+(Complex<T>& c)
  38. {
  39.         Complex<T> tmp(this->a + c.a, this->b + c.b);
  40.         return tmp;
  41. }

  42. void main()
  43. {
  44.         Complex<int> c1(111, 222);
  45.         Complex<int> c2(333, 444);
  46.         cout << c1 << c2 << endl;

  47.         Complex<int> c3 = c1 + c2;
  48.         cout << c3 << endl;
  49.         system("pause");
  50. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-5-8 16:23:22 | 显示全部楼层
friend ostream& operator<<(ostream& out,Test<T>& t);
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-5-9 10:44:31 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-30 23:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表