友元函数实现复数加减法

C++程序:友元函数重载复数减法在dev-C++ 5.11下运行没有问题,但是在vc6.0运行时提示错误。
(自考C++程序设计2019年版,程序4-1,例4-2、程序4-2等有同样问题)
程序代码如下:

#程序4-1
#include <iostream>
using namespace std;
class myComplex			//复数类
{
private:
	double real,imag; 
public:
	myComplex(double r=0,double i=0){	real=r;	imag=i;}	//构造函数
	void outCom(){	cout<<"("<<real<<","<<imag<<")";}						//成员函数 
	myComplex operator-(const myComplex &c);		//成员函数
	friend myComplex operator+(const myComplex &c1,const myComplex &c2);//友元 
 };
myComplex myComplex::operator-(const myComplex &c)
{	return myComplex(this->real-c.real,this->imag-c.imag);}		//返回一个临时对象 
myComplex operator+(const myComplex &c1,const myComplex &c2)
{	return myComplex(c1.real+c2.real,c1.imag+c2.imag);	}	//返回一个临时对象 
int main()
{
	myComplex c1(1,2),c2(3,4),res;
	c1.outCom();	cout<<"operator+";	c2.outCom();	cout<<"=";
	res=c1+c2;	res.outCom();	cout<<endl;
	c1.outCom();	cout<<"operator-";	c2.outCom();	cout<<"=";
	res=c1-c2;	res.outCom();	cout<<endl;
	return 0; 
}

在dev-C++ 5.11下运行没有问题,但是在vc6.0运行时提示错误:
Compiling…
pro4-1.cpp
d:\ftp\cpp\pro4-1.cpp(11) : fatal error C1001: INTERNAL COMPILER ERROR
(compiler file ‘msc1.cpp’, line 1786)
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
Error executing cl.exe.

pro4-1.obj - 1 error(s), 0 warning(s)
百度了一下,一种解释为:
有些C++编译系统(例如Visual C++ 6.0)没有完全实现C++标准,它所提供的不带后缀.h的头文件不支持把运算符重载作为友元函数,所以编写运算符重载作为友元函数时,在Visual C++系统中编译时会出错,这里提供两种解决方案:
(1) 由于Visual C++所提供的老版本的带后缀.h的头文件可以支持此项功能,因此可以将程序头两行改一下。原来的程序为:

#include <iostream>
using namespace std;

改为:

#include <iostream.h>

经验证:可行。
后面在程序4-2中,用到string类对象s,无法使用,只好改为char *s。
<string.h>是C版本的头文件,包含比如strcpy、strcat之类的字符串处理函数。
< cstring>实现同<string.h>相同或兼容。
< string>定义了一个string的字符串类,还加了#include<string.h>包含了C版本的字符串操作。

(2)在复数类前增加
class myComplex;
myComplex operator+(const myComplex &c1,const myComplex &c2);
也可运行。
后面在程序4-2中,也在复数类前加上类的声明和6个友元函数的声明,可以运行。

参考:https://blog.csdn.net/weixin_34417814/article/details/92631106

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值