templateclass Complex{ public: Complex(T a, T b){ this->a = a; this->b = b; } void print(){ cout << "Complex a: " << a << " b: " << b << endl; } Complex operator+(Complex &c){ Complex temp(a + c.a, b + c.b); return temp; } //friend ostream& operator << (ostream& out, Complex c); //friend istream& operator>> (istream& in, Complex& c); //这样依然满足模板化 friend ostream & operator << (ostream& out, Complex c){ out << "complex a: " << c.a << " b: " << c.b; return out; } friend istream & operator>> (istream& in, Complex &c){ cout << "enter a:"; in >> c.a; cout << "enter b:"; in >> c.b; return in; } protected: private: T a; T b; }; //运算符重载的正规写法:重载<< >>只能用友元函数,其他的运算符都要写成成员函数 避免打破封装性 //写在类内部 否则失去模板作用 必须强制说明类型 //ostream & operator << (ostream& out, Complex c){ // out << "complex a: " << c.a << " b: " << c.b ; // return out; //} //istream & operator>> (istream& in, Complex &c){ // cout << "enter a:"; // in >> c.a; // cout << "enter b:"; // in >> c.b; // return in; //} Main: Complex c1(10, 20); Complex c2(15, 25); Complex c3 = c1 + c2; //c3.print(); cout << c3 << endl;;
类模板中的static关键字:
templateclass Test{ public: Test(T a){ this->m_a = a; m_b = 12; } void print(){ cout << "this is m_a: " << m_a << " this is m_b addr: " << &m_b << endl;; } private: T m_a; static T m_b; }; template T Test ::m_b = 0; Main: Test t1(5); Test t2(10.000); t1.print(); //this is m_a: 5 this is m_b addr: 00D70358 t2.print();//this is m_a: 10 this is m_b addr: 00D70320 注意 m_b的地址变了 //模板类不会共用一份static变量(除非类型一致) 如Test t1(5);Test t2(10.000); 此时m_b地址相同 //Test t1(5);Test t2(10.000); 此时m_b地址不同 //原理:c++编译器帮程序员省略了解析和设定类型 如Test t1(5),int Test ::m_b = 0; Test t2(10.000), Test ::m_b = 0; 即开辟了不同类型的static变量的空间



