琴长不过时光 发表于 2020-5-8 12:16:18

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

#include "iostream"
using std::endl;
using std::cout;
using std::cin;
using std::ostream;

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

template <typename T>
Complex<T>::Complex<T>(T a, T b)
{
        this->a = a;
        this->b = b;
}

template <typename T>
void Complex<T>::printCom()
{
        cout << this->a << " " << this->b << endl;
}

template <typename T>
ostream& operator<<(ostream& out, Complex<T>& c)
{
        out << c.a << " " << c.b << endl;
        return out;
}

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

void main()
{
        Complex<int> c1(111, 222);
        Complex<int> c2(333, 444);
        cout << c1 << c2 << endl;

        Complex<int> c3 = c1 + c2;
        cout << c3 << endl;
        system("pause");
}

梦想灬远帆 发表于 2020-5-8 16:23:22

friend ostream& operator<<(ostream& out,Test<T>& t);

琴长不过时光 发表于 2020-5-9 10:44:31

页: [1]
查看完整版本: 小白求助 关于模板类的问题