正确的程序如下:
#include<iostream.h>//a
class RMB
{
int yuan,jiao;
public:
RMB(int y=0,int j=0)
{
yuan=y;
jiao=j;
}
void display()
{
cout<<yuan<<"元"<<jiao<<"角\n";
}
friend RMB operator+(const RMB& a,const RMB& b);
};
RMB operator+(const RMB& a,const RMB& b)
{
RMB temp;
temp.yuan=a.yuan+b.yuan;
temp.jiao=a.jiao+b.jiao;
if(temp.jiao>=10)
{
temp.yuan++;
temp.jiao-=10;
}
return temp;
}
void main()
{
RMB s(7,6),t(8,7);
RMB m;
m=s+t;
m.display();
}
将程序作如下修改,就会出现我不能理解的错误:
1:将a处的语句改成:
#include<iostream>
using namespace std;
错误好下:
E:\vc++\SOFTWA~2\VC60\MyProjects\xieyou\01.cpp(16) : 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
2:将友元函数RMB operator+(const RMB& a,const RMB& b)变为RMB类的成员函数,程序如下:
#include<iostream.h>
class RMB
{
int yuan,jiao;
public:
RMB(int y=0,int j=0)
{
yuan=y;
jiao=j;
}
void display()
{
cout<<yuan<<"元"<<jiao<<"角\n";
}
RMB operator+(RMB& a,RMB& b)
{
RMB temp;
temp.yuan=a.yuan+b.yuan;
temp.jiao=a.jiao+b.jiao;
if(temp.jiao>=10)
{
temp.yuan++;
temp.jiao-=10;
}
return temp;
}
};
void main()
{
RMB s(7,6),t(8,7);
RMB m;
m=s+t;
m.display();
}
错误如下:
e:\vc++\softwa~2\vc60\myprojects\xieyou\01.cpp(16) : error C2804: binary 'operator +' has too many parameters
e:\vc++\softwa~2\vc60\myprojects\xieyou\01.cpp(16) : error C2333: '+' : error in function declaration; skipping function body
e:\vc++\softwa~2\vc60\myprojects\xieyou\01.cpp(33) : error C2676: binary '+' : 'class RMB' does not define this operator or a conversion to a type acceptable to the predefined operator
而这时再在operator+(const RMB& a,const RMB& b)加上friend又没有错了:这函数明明是RMB类的成员函数为什么还要声明为RMB类的友元函数。
另外:程序作如下变换也正确:
#include<iostream.h>
class RMB
{
int yuan,jiao;
public:
RMB(int y=0,int j=0)
{
yuan=y;
jiao=j;
}
void display()
{
cout<<yuan<<"元"<<jiao<<"角\n";
}
RMB operator+(RMB& b)
{
RMB temp;
temp.yuan=yuan+b.yuan;
temp.jiao=jiao+b.jiao;
if(temp.jiao>=10)
{
temp.yuan++;
temp.jiao-=10;
}
return temp;
}
};
void main()
{
RMB s(7,6),t(8,7);
RMB m;
m=s+t;
m.display();
}
本人初学VC++,如有语言叙述错误还望见谅。
希望大家帮我解释一下,在此先谢过了。
[求助]vc++关于操作符重载的问题。