类的运算符重载的事例

 1 #include<iostream>
 2 using namespace std;
 3 class DoubleMath{
 4 int high;
 5 int *th;
 6 public :
 7     DoubleMath(int h,int*it);
 8     DoubleMath(DoubleMath & it);
 9     ~DoubleMath(){delete th;}
10     void build();
11     friend DoubleMath operator+(DoubleMath & one, DoubleMath & two);
12     friend void showit(DoubleMath&);
13 };
14 
15 DoubleMath::DoubleMath(int h,int*it):high(h){
16 th = new int[h];
17 for(int i=0;i<h;i++)
18      th[i]=it[i];
19 }
20 DoubleMath::DoubleMath(DoubleMath & it){
21     high  = it.high;
22     th = new int[high];
23     for(int i=0;i<it.high;i++)
24         th[i] = it.th[i];
25 }
26 
27 DoubleMath operator+(DoubleMath & one,DoubleMath & two){
28     int max = one.high>two.high?one.high:two.high;
29     int min = one.high<two.high?one.high:two.high;
30     int*gh = new int[max];
31     for(int i=0;i<min;i++)
32         gh[i]=(one.th[i]+two.th[i])%2;
33     if(max==one.high)  
34         for(int i=min;i<one.high;i++)
35             gh[i]= one.th[i];
36     else 
37         for(int i = min;i<two.high;i++)
38             gh[i]= two.th[i];
39     DoubleMath plusth(max,gh);
40     return plusth;
41 }
42 
43 void showit(DoubleMath&it){
44     cout<<it.high<<" ";
45     for(int i=it.high-1;i>0;i--)
46         cout<<it.th[i]<<" ";
47     cout<<it.th[0]<<endl;
48 }
49 
50 int main(){
51 int num;
52 cin>>num;
53 for(int i=0;i<num;i++)
54 {
55    int *th1;
56    int high1;
57    int*th2;
58    int high2;
59    cin>>high1;
60    th1 = new int[high1];
61    for(int i = high1-1;i>=0;i--)
62         cin>>th1[i];
63   cin>>high2;
64    th2 = new int[high2];
65    for(int i = high2-1;i>=0;i--)
66         cin>>th2[i];
67    DoubleMath one(high1,th1);
68    DoubleMath two(high2,th2);
69   DoubleMath three = one + two;
70   showit(three);
71  delete th1,th2;
72 }
73 
74 }

 

Problem D: 1,2,3班_Contest1_Q4

Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 347  Solved: 151 [Submit][Status][Web Board]

Description

(考察运算符重载)
考虑系数只能为0和1的多项式,而这种多项式的加法很特别,它是类似一个异或操作(不进位加),即:(0 + 0) mod 2 = 0, (0 + 1) mod 2 = 1, (1 + 0) mod 2 = 1, and (1 + 1) mod 2 = 0,
如:(x^6 + x^4 + x^2 + x + 1) + (x^7 + x + 1) = x^7 + x^6 + x^4 + x^2
其实减法也是不进位加,如:
   (x^6 + x^4 + x^2 + x + 1) - (x^7 + x + 1) = x^7 + x^6 + x^4 + x^2
现要求设计一个多项式类,并重载加号操作符,多项式类的其他方法和成员变量请根据需要自行设计。

Input

输入的第一行,表示后续包括T个测试样例。而每个测试样例的第一行表示加法运算的第一个多项式f(x),第二行表示多项式g(x)。其中每行开始的数字代表该多项式的最高次数+1,其后的多项式系数按多项式次数递减排列。详见输入范例。

Output

每个测试样例的乘法运算结果占一行。

Sample Input

1 
7 1 0 1 0 1 1 1 
8 1 0 0 0 0 0 1 1

Sample Output

8 1 1 0 1 0 1 0 0 



HINT

posted on 2013-04-23 23:31  Besion王  阅读(209)  评论(0编辑  收藏  举报

导航