您的位置:首页 > 编程语言 > C语言/C++

C++模板及operator重载测试实例(vs 2008)

2010-02-01 14:20 435 查看
myoperator.h文件:

#ifndef _MYOPERATOR_H
#define _MYOPERATOR_H
using std::ostream;
template<typename T>
class Point
{
T x;
T y;

public:
Point();
Point(const T x, const T y);
//拷贝构造函数重载
Point( Point& p);
//+运算符重载
Point& operator+(Point& p);
//赋值运算符重载
Point& operator=(Point& p);
void display() const;
template<class T>
friend ostream& operator<<(ostream& out, Point& p);
};

template<typename T1, typename T2>
class Person
{
T1 name;
T2 age;
public:
Person(const T1 name, const T2 age);
//类型重载
operator T1();
operator T2();
void show() const;
};

#endif


TestOperator.cpp文件:

#include <iostream>
#include <string>
#include "myoperator.h"

using namespace std;

template <typename T>
Point<T>::Point()
{
cout<<"无参构造器"<<endl;
}

template <typename T>
Point<T>::Point(const T x, const T y):x(x), y(y)
{
cout<<"两个参数构造器"<<endl;
}

//拷贝构造函数重载
template <typename T>
Point<T>::Point(Point<T>& p):x(p.x),y(p.y)
{
cout<<"拷贝构造函数"<<endl;
}

//赋值运算符重载
template <typename T>
Point<T>& Point<T>::operator =(Point<T> &p)
{
this->x = p.x;
this->y = p.y;
return *this;
}

//+运算符重载
template <typename T>
Point<T>& Point<T>::operator +(Point<T>& p)
{
this->x += p.x;
this->y += p.y;
return *this;
}

template <typename T>
void Point<T>::display() const
{
cout<<"("<<x<<","<<y<<")"<<endl;
}

template <typename T>
ostream& operator<<(ostream& out, Point<T> &p)
{
out<<"("<<p.x<<","<<p.y<<")"<<endl;
return out;
}

template <typename T1, typename T2>
Person<T1, T2>::Person(const T1 name, const T2 age): name(name),age(age)
{
}

//T1类型重载
template <typename T1, typename T2>
Person<T1, T2>::operator T1()
{
return name;
}

//T2类型重载
template <typename T1, typename T2>
Person<T1, T2>::operator T2()
{
return age;
}

template <typename T1, typename T2>
void Person<T1, T2>::show() const
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
}

int main()
{

Point<double> p1(1.0, 1.0);
//拷贝构造函数重载测试
Point<double> p2(p1);

//赋值运算符重载测试
//p2 = p1;

//ostream重载测试
cout<<p2;

p2.display();

//类型重载测试
Person<string, int> person("Jack", 21);
string name = person;
int age = person;

cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
//person.show();
return 0;
}


运行结果:

两个参数构造器
拷贝构造函数
(1,1)
(1,1)
Name: Jack
Age: 21
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: