| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 616 人关注过本帖
标题:问一个重载操作符的问题,谢谢
取消只看楼主 加入收藏
flyingni
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2007-9-8
收藏
 问题点数:0 回复次数:3 
问一个重载操作符的问题,谢谢
我自己编写了一个类,然后重载了相应的操作符(+,-,<<,>>等)
a,b,c都是这个类的对象
cout<<"a+c is "<< a+c <<"\n";
编译器就抱错说找不到相应的类型之类的
然后改称
d=a+c;
cout<<"a+c is "<< d <<"\n";
就好了,为啥会这样
谢谢啦
搜索更多相关主题的帖子: 操作符 重载 
2007-09-20 22:07
flyingni
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2007-9-8
收藏
得分:0 
回复:(flyingni)问一个重载操作符的问题,谢谢

complex.cpp
#include <iostream>
#include "complex0.h"

complex::complex(double r,double i)
{
real=r;
imaginary=i;
}

complex::complex()
{
real=imaginary=0;
}

complex complex::operator+(const complex & c)const
{
return complex(real+c.real,imaginary+c.imaginary);
}

complex complex::operator-(const complex & c)const
{
return complex(real-c.real,imaginary-c.imaginary);
}

complex complex::operator*(const complex & c)const
{
return complex(real*c.real-imaginary*c.imaginary,real*c.imaginary+imaginary*c.real);
}

complex complex::operator~()const
{
return complex(real,-imaginary);
}

std::ostream & operator<<(const std::ostream & os,complex & c)
{
std::cout<<"("<<c.real<<", "<<c.imaginary<<")";
}

bool operator>>(const std::istream & is,complex & c)
{
std::cout<<"real:";
if (std::cin>>c.real)
{
std::cout<<"\nimaginary:";
std::cin>>c.imaginary;
return 1;
}
else
return 0;
}

complex operator*(double num,complex & c)
{
return complex(num*c.real,num*c.imaginary);
}

complexmain.cpp
#include <iostream>
#include "complex0.h"

int main()
{
using namespace std;
complex a(3.0,4.0);
complex c,b,d,e,f,g;
cout<<"Enter a complex number (q to quti):\n";
while(cin>>c)
{
cout<<"c is "<< c <<"\n";
b=~c;
cout<<"complex conjugate is " << b <<"\n";
cout<<"a is "<< a <<"\n";
d=a+c;
cout<<"a+c is "<< d <<"\n";
e=a-c;
cout<<"a-c is "<< e <<"\n";
f=a*c;
cout<<"a*c is "<< f <<"\n";
g=2*c;
cout<<"2*c is "<< g <<"\n";
cout<<"Enter a complex number (q to quit):\n";
}
cout<<"Done\n";
return 0;
}

2007-09-20 22:36
flyingni
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2007-9-8
收藏
得分:0 
回复:(flyingni)回复:(flyingni)问一个重载操作...
如果你的主程序变成下面这样
int main()
{
//name object1("jkkj","kjh");
cout<<object1;
//name object2(" kjh ","kjh");
cout<<object1+object2;
system("pause");
return 0;
}
还能行吗?我的程序变成这样就不行了,如果想要这样可以的话,要怎么写?
2007-09-20 22:44
flyingni
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2007-9-8
收藏
得分:0 
回复:(suwenyi)你对的重载有问题...
我的程序已经运行过了啊,这个返回值如果要写得话应该怎么写?
2007-09-21 20:25
快速回复:问一个重载操作符的问题,谢谢
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.017863 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved