重载了运算符。。但是程序却不能运行,,,求解释。。。
#include"iostream"
using std::cout;
using std::ostream;
using std::istream;
using std::endl;
using std::cin;
class fraction{
private:
int mol; //分子
int den; //分母
public:
fraction(int a=0,int b=0):mol(a),den(b){};
fraction* operator+(fraction b)
{
fraction* a;
a=new fraction;
a->mol=this->mol+b.mol;
a->den=this->den*b.den;
return(*a);
}
friend ostream &operator<<(ostream &os,fraction &b);
bool operator>(fraction b)
{
if((this->mol==b.mol)&&(this->den!=b.den))
if(this->den>b.den)
return false;
else if((this->mol!=b.mol)&&(this->den==b.den))
if(this->mol<b.mol)
return false;
else
return true;
}
};
ostream &operator<<(ostream &os,fraction &b)
{
os << b.mol << "" << b.den << endl;
return os;
}
void main()
{
fraction A(1,2),B(1,3);
cout << (A+B) << endl;
if(A>B)
cout << A << "大" << endl;
else
cout << B << "大" << endl;
}
E:\编程\数据结构\33.cpp(19) : error C2440: 'return' : cannot convert from 'class fraction' to 'class fraction *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
E:\编程\数据结构\33.cpp(37) : error C2001: newline in constant
E:\编程\数据结构\33.cpp(38) : error C2143: syntax error : missing ';' before 'return'
执行 cl.exe 时出错.
[解决办法]
19行那里,return a就可以了,a已经是一个指针变量了!不用return (*a),画蛇添足!
37行那里,""应写作"\",因为\是个转义字符!
38行的错误是37行导致的!
[解决办法]
#include <iostream>
using namespace std;
class fraction {
private:
int mol; //分子
int den; //分母
public:
fraction(int a=0,int b=1) : mol(a),den(b){}
fraction operator+(const fraction &b)
{
return fraction(mol * b.den + den * b.mol, den * b.den);
}
friend ostream &operator<<(ostream &os, const fraction &b);
bool operator>(const fraction &b) const
{
bool ret = (den > 0) == (b.den > 0);
return ret == (mol * b.den > den * b.mol);
}
};
ostream &operator<<(ostream &os, const fraction &b)
{
return os << b.mol << "" << b.den << endl;
}
void main()
{
fraction A(1,2),B(1,3);
cout << (A+B) << endl;
if(A>B)
cout << A << "大" << endl;
else
cout << B << "大" << endl;
}