c++实验(模板)

#include
//8.1
using namespace std;

template
class Complex
{
T R,I;
public:
Complex(T a=0,T b=0){R=a;I=b;}
Complex operator+(Complex c);
void show()
{
cout<<R<<" "<<I<<endl;
}
};

template
Complex Complex::operator+(Complex c)
{
Complex t;
t.R=R+c.R;
t.I=I+c.I;
return t;

}
int main()
{
Complexc1(10,20),c2(6,5),c3;
c3=c1+c2;
c3.show();
return 0;
}
//8.2
#include

using namespace std;

template
class Shape
{
T x,y;
public:
Shape(T a,T b){x=a;y=b;}
Shape &operator++()
{
x++;
y++;
return *this;
}
void print()
{
cout<<x<<" "<<y<<endl;
}
~Shape()
{
cout<<“Shape is over”<<endl;
}
};

int main()
{
Shape p1(10,20);
++p1;
p1.print();
return 0;
}
//8.3
#include

using namespace std;

template
class Test
{
T x,y;
public:
Test(T a=0,T b=0){x=a;y=b;}
Test operator+(Test);
Test operator=(Test);
void show()
{
cout<<x<<" "<<y<<endl;
}
};
template
Test Test::operator=(Test a)
{
x=a.x;
y=a.y;
return *this;
}

template
Test Test::operator+(Test a)
{
x+=a.x;
y+=a.y;
return *this;
}

int main()
{
Testt1(1,2),t2(3,4),t3;
t3=t1+t2;
t3.show();
return 0;
}

猜你喜欢

转载自blog.csdn.net/cruel2436/article/details/84333136