C++笔试专题一:运算符重载

一:下面重载乘法运算符的函数原型声明中正确的是:(网易2016校招)

  A:MyClass operator *(double ,MyClass);
  B:MyClass operator *(MyClass ,MyClass);
  C:MyClass operator *(double ,double);
  D:MyClass operator *(MyClass ,double);
答案ABD:c++中规定,重载运算符必须和用户定义的自定义类型的对象一起使用。
 
二:如果友元函数重载一个运算符时,其参数表中没有任何参数则说明该运算符是:(迅雷)
  A:一元运算符
  B:二元运算符
  C:A或者B都可以
  D:重载错误
答案D:友元函数无this指针。

三:若要对data类中重载的加法运算符成员函数进行声明,下列选项中正确的是?(百度)

  A:Data operator+(Data);

  B:Data operator(Data);

  C:operator+(Data,Data);

  D:Data+(Data);

答案选A:成员函数,双目单参数,默认this做左参数。

  
 1 /*c++运算符重载****************/
 2 /********************
 3 5类运算符不能重载:关系运算符.,成员指针运算符*,作用于分辨符*,sizeof运算符,三目运算符:?
 4 不能改变运算符的操作数个数
 5 不能改变原有运算符的优先级
 6 不能改变运算符原有的结合特性
 7 不能改变运算符对与定义类型数据的操作方式。
 8 ********************
 9 运算符重载有两种方式:
10 1:友元函数
11     friend 类型 operator@(参数表);类外不需要加friend
12     不能重载的四个:= () [] ->
13 2:成员函数
14     类型 operator@(参数表)
15     参数默认传入了一个this
16 *********************/
17 
18 
19 #include <iostream>
20 using namespace std;
21 
22 class complex{
23 private:
24     double real,imag;
25 public:
26     complex(double r = 0,double i = 0){
27         real = r;
28         imag = i;
29     }
30     friend complex operator+(complex om1,complex om2);
31     friend complex operator*(complex om1,complex om2);
32     friend complex operator -(complex om1);
33     friend void operator ++(complex& om1,int);
34     complex operator-(complex om1);
35     void print(){
36         cout<<real;
37         if(imag>0)
38             cout<<"+";
39         if(imag!=0)
40             cout<<imag<<"i\n";
41     }
42 };
43 //取负
44 complex operator-(complex om1){
45     return complex(-om1.real,-om1.imag);
46 }
47 
48 //++
49 void operator++(complex& om1,int){
50     om1.real++;
51     om1.imag++;
52 }
53 
54 //重载+
55 complex operator+(complex om1,complex om2){
56     /*
57     complex temp;
58     temp.real = om1.real+om2.real;
59     temp.imag = om1.imag+om2.imag;
60     return temp;
61     */
62     return complex(om1.real+om2.real,om1.imag+om2.imag);
63 }
64 
65 //重载*
66 complex operator*(complex om1,complex om2){
67     complex temp;
68     temp.real = om1.real*om2.real-om1.imag*om2.imag;
69     temp.imag = om1.real*om2.imag-om1.imag*om2.real;
70     return temp;
71 }
72 
73 //重载-。成员函数方式
74 complex complex::operator-(complex om1){
75     complex temp;
76     temp.real = real-om1.real;
77     temp.imag = imag-om1.imag;
78     return temp;
79 }
80 
81 int main(){
82     complex com1(1.1,2.2),com2(3.3,4.4),total,total2,total3,total1;
83     //total = com1+com2;
84     total= operator+(com1,com2);
85     total1 = com1-com2;
86     total2 = com1*com2;
87     total3 = -com1;
88     total.print();
89     total1.print();
90     total2.print();
91     total3.print();
92     total++;
93     total.print();
94     return 0;
95 }

 

posted @ 2017-02-10 14:28  圆滚滚的小峰峰  阅读(689)  评论(0编辑  收藏  举报