模板类的友员函数
2017-05-05 23:24
351 查看
#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;
}
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;
}
相关文章推荐
- 模板类的成员函数指针的使用
- 模板类作为类成员
- mediawiki中,SkinTemplate->template用于设置模板类名称
- [转] PHPlib Template 模板类中文文档
- Delphi里的模板类
- 模板类的特化
- 模板类(Map和set)
- 从Discuz中抠出的模板类
- WorkflowRuntime与宿主,服务,工作流模板类,设计器,实例的关系
- 模板函数,函数模板,模板类,类模板的区别
- c++模板类/模板函数的声明与定义应该放在头文件里
- 利用模板类生成的循环单链表实现约瑟夫问题。
- 模板类 与 类模板
- c++模板函数和模板类简单应用举例
- 友元模板类使用
- 类模板与模板类及其使用
- C++模板类
- 在VC6里把偏特化后的模板类(或者整个模板类族)声明为另一个类的友元的方法
- 模板类的使用---模板类,最好连同实现都放到.h里头
- C++11: 使用 lambda 创建模板类 的 对象