Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3922421
  • 博文数量: 356
  • 博客积分: 10458
  • 博客等级: 上将
  • 技术积分: 4734
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-24 14:59
文章分类

全部博文(356)

文章存档

2020年(17)

2019年(9)

2018年(26)

2017年(5)

2016年(11)

2015年(20)

2014年(2)

2013年(17)

2012年(15)

2011年(4)

2010年(7)

2009年(14)

2008年(209)

分类: C/C++

2008-05-15 18:33:36

#include <iostream>
using namespace std;
class complex{
    private:
        int real,imag;
    public:
        complex(int r=0,int i=0):real(r),imag(i){}
        friend complex operator +(complex c1);
        friend complex operator -(complex c1);
        void diplay();
};
void complex::diplay(){cout < <"real:" < <real < <"imag:" < <imag < <endl;}

complex operator +(complex c1){
    return complex(real+c1.real, imag+c1.imag);
}
complex operator -(complex c1){
    return complex(real-c1.real,imag-c1.imag);
}
int main(){
    complex c1(1,2),c2(2,3),c3;
    c1.diplay();
    c2.diplay();
    c3=c1+c2;
    c3.diplay();
    c3=c1-c2;
    c3.diplay();
}
//此处不能通过,没想通,面下面这个就可以运行,不知为什么?
#include <iostream>
using namespace std;
class complex{
    private:
        int real,imag;
    public:
        complex(int r,int i);
        void display();
        friend complex operator +(complex c1,complex c2);
        friend complex operator -(complex c1,complex c2);
};
complex::complex(int r,int i){
    real=r;
    imag=i;
}
complex complex::operator +(complex c1,complex c2){
    return complex(c1.real+c2.real,c1.imag+c2.imag);
}
complex complex::operator -(complex c1,complex c2){
    return complex(c1.real-c2.real,c1.imag-c2.imag);
}
void complex::display(){
    cout < <"real=" < <real < <"imag=" < <imag < <endl;
}
int main(){

}

因为如果是friend的话 参数必须显示有两个操作对象
而非friend的  因为其本身隐含了一个this参数 所以不要两个 

所以你第一个可行 第二个不行  把friend去掉就可以了

 

class complex{
    private:
        int real,imag;
    public:
        complex(int r=0,int i=0):real(r),imag(i){}
         complex operator +( complex c1);
          complex operator -( complex c1);
        void diplay();
};
void complex::diplay(){cout <<"real:" <<real <<"imag:" <<imag <<endl;}

complex complex::operator +(complex c1){
    return complex(real+c1.real, imag+c1.imag);
}
complex complex::operator -( complex c1){
    return complex(real-c1.real,imag-c1.imag);
}
int main(){
    complex c1(1,2),c2(2,3),c3;
    c1.diplay();
    c2.diplay();
    c3=c1+c2;
    c3.diplay();
    c3=c1-c2;
    c3.diplay();
}

输出如下
real:1imag:2
real:2imag:
3
real:3imag:
5
real:
-1imag:-1
Press any key to
continue
阅读(3144) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~