欢迎访问成都祈钰瑶科技有限公司!

全国免费服务热线:

18982081108
✕

成都网站设计公司,成都响应式网站设计,成都移动端网站设计,成都网站UI设计

模板类的友员函数

#include<iostream>

创新互联是专业的桥西网站建设公司,桥西接单;提供成都网站建设、网站设计,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行桥西网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

using namespace std;

template<class T>

class Complex{

public:

Complex(T a, T b);

void setComplex(T a,T b);

friend Complex<T> operator+(const Complex<T> &c1, const Complex<T> &c2){

//对于模板类的友员函数一定要写在类内!!!不可以再类外实现

T p_w_picpath = c1.p_w_picpath + c2.p_w_picpath;

T real = c1.real + c2.real;

return Complex<T>(real,p_w_picpath);

//这个必须按照这样写,不能加个对象!因为类型不确定!

}

friend Complex<T>operator-(const Complex<T> &c1, const Complex<T> &c2){

T p_w_picpath = c1.p_w_picpath - c2.p_w_picpath;

T real = c1.real - c2.real;

return Complex<T>(real,p_w_picpath);

}

friend Complex<T> operator-(const Complex &c1){

return Complex<T> (-c1.real, -c1.p_w_picpath);

}

void print()const;

private:

T real, p_w_picpath;

};

template <class T>

Complex<T>::Complex(T a, T b){

setComplex(a, b);

}

template<class T>

void Complex<T>::print()const{

cout << "real=" << real << "p_w_picpath=" << p_w_picpath << endl;

}

template <class T>

void Complex<T>::setComplex(T a, T b){

real = a;

p_w_picpath = b;

}

int main(){

Complex<int> a(2, 3);

Complex<int> b(2, 4);

(a + b).print();

(a - b).print();

(-a).print();

system("pause");

return 0;

}