//模仿段
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class numtype>
//定义类模板
class Compare
{
public :
Compare(numtype a,numtype b)
{x=a;y=b;}
numtype max( )
{return (x>y)?x:y;}
numtype min( )
{return (x<y)?x:y;}
private :
numtype x,y;
};
int main( )
{
Compare<int > cmp1(3,7); //定义对象cmp1,用于两个整数的比较
cout<<cmp1.max( )<<" is the Maximum of two integer numbers."<<endl;
cout<<cmp1.min( )<<" is the Minimum of two integer numbers."<<endl<<endl;
Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较
cout<<cmp2.max( )<<" is the Maximum of two float numbers."<<endl;
cout<<cmp2.min( )<<" is the Minimum of two float numbers."<<endl<<endl;
return 0;
}
//自编段
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
template <class T>
class Cylinder
{
private:
Cylinder m_r,m_x,m_y,m_h,PI=3;
public:
Cylinder(){m_r=0;m_x=0;m_y=0;m_h=0;}
Cylinder(T r,T x,T y,T h){ m_r=r;m_x=x;m_y=y;m_h=h;}
Cylinder GetVolume() { return V=PI*m_r*m_r*m_h;}
Cylinder GetSurface(){ return S=2*PI*m_h*m_r+PI*m_r*m_r;}
};
int main()
{ Cylinder<int> a (1,1,1,1);
cout<<a.GetSurface()<<"是圆柱体的体积"<<endl;
cout<<a.GetSurface()<<"是圆柱体的表面积"<<endl;
return 0;}
自编段在主函数cout<<中显示没有与这些操作数匹配的“<<",要重载运算符吗?怎么重载?为什么自编段里就需要重载呢?
没有定义变量 V 和 S
程序的运行是依赖于环境的支持的,比如说别人的电脑上有程序运行所需要的某个文件(或者控件、组件、插件等等),而你的电脑上没有,那就会报错了。