C++模板及operator重载测试实例(vs 2008)
2010-02-01 14:20
435 查看
myoperator.h文件:
TestOperator.cpp文件:
运行结果:
两个参数构造器
拷贝构造函数
(1,1)
(1,1)
Name: Jack
Age: 21
#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
相关文章推荐
- C++ VS 2008中ATL的创建,使用。并在C++项目中进行调用测试
- VS 2008 修改C++文件默认模板
- c++ 模板函数,类模板,仿函数使用实例代码
- VS 2008 修改模板页
- C++重载operator的示例
- c++实现数据结构链表的插入 删除 倒置 取值(vs测试可以运行)
- C++里用类重载数据类型模板
- C++ 函数模板(十四)--template 泛型函数模板、通用函数、重载模板
- Linux下: Eclipse安装配置OpenCV2.1,用C++调用OpenCV过程 及 测试实例
- C++基于该模型模板包括节目外实例
- libmemcached1.0.2 C/C++ API使用实例、测试及修改
- C++ 类模板概念与实例,模板参数问题
- Ctrl+k Ctrl+D VS2008 C++
- C++ VS 2008中ATL的创建,使用。并在C++项目以及C#项目中进行调用测试
- C++模板技术实例(1)
- C++重载operator的示例
- [C++] 测试硬件popcnt(位1计数)指令与各种软件算法,利用模板实现静态多态优化性能
- [置顶] c++ 函数模板重载(数组和指针 一级指针和二级指针)
- 运算符重载 编程题#2(Coursera 程序设计与算法 专项课程3 C++程序设计;重载:& operator-)
- c++ 模板的重载