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