码迷,mamicode.com
首页 > 其他好文 > 详细

模板类的友员函数

时间:2017-05-06 10:13:40      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:complex   friend   public   return   

#include<iostream>

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 image = c1.image + c2.image;

T real = c1.real + c2.real;

return Complex<T>(real,image);

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

}

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

T image = c1.image - c2.image;

T real = c1.real - c2.real;

return Complex<T>(real,image);

}

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

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

}

void print()const;

private:

T real, image;

};

template <class T>

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

setComplex(a, b);

}

template<class T>

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

cout << "real=" << real << "image=" << image << endl;

}

template <class T>

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

real = a;

image = 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;

}


模板类的友员函数

标签:complex   friend   public   return   

原文地址:http://ji123.blog.51cto.com/11333309/1922587

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!