当我执行运算符重载时,我在'&'token 之前得到了这个错误,预期构造函数、析构函数或类型转换。错误发生在 fixed.cpp 的最后 8 行中,我不确定我错过了什么。任何帮助表示赞赏。
这是固定的.hpp
#ifndef FIXED_HPP_
#define FIXED_HPP_
typedef float value_type ;
class fixed
{
public:
fixed();
fixed(value_type integer, value_type fraction);
fixed(double val);
void as_string();
value_type integer();
value_type fraction();
value_type value();
//~fixed();
fixed& operator+=(fixed other);
static const int places=4;
static const int places10=10000;
private:
value_type integer_;
value_type fraction_;
value_type value_;
};
fixed operator+(fixed a, fixed b);
#endif
这是固定的.cpp:
#include "fixed.hpp"
#include <iostream>
#include <ostream>
#include <stdexcept>
#include <string>
#include <algorithm>
using namespace std;
fixed::fixed():integer_(0), fraction_(0), value_(0){}
fixed::fixed(value_type integer, value_type fraction):integer_(integer), fraction_(fraction)
{try
{
if (fraction_ <0)
throw invalid_argument("Invalid argument. Must be positive.");
}
catch (exception& e)
{
cout <<"\n"<< e.what() << std::endl;
}
while (fraction_>= places10)
{
if(int(fraction_)%10 >=5 && fraction_< (places10*10) )
fraction_=int(fraction_/10+1);
else
fraction_ =int(fraction_/10);
}
value_ = integer_*places10 + fraction_;
}
fixed::fixed(double val):integer_(int (val)), fraction_( (val- int(val))*places10)
{ if (val <0)
{ val = val*(-1);
if ( int(val*places10*10)%10>=5)
fraction_ = (fraction_*(-1) +1)*(-1);
}
else
{
if (int(val*places10*10)%10>=5)
fraction_ = fraction_ +1;
}
value_ = integer_*places10 + fraction_;
}
void fixed::as_string()
{ string str;
string str2;
while( (int(integer_)/10) >=0 and int(integer_)>0 )
{
str.push_back(int(integer_)%10 + 48);
integer_ = integer_/10;
//cout<<str<<endl;
}
//cout<<"String format: "<<str<<endl;
reverse(str.begin(), str.end());
//cout<<"Reversed format: "<<str<<endl;
str.push_back('.');
//cout<<"New string: "<<str<<endl;
while( (int(fraction_)/10 )>=0 and int(fraction_)>0)
{
str2.push_back(int(fraction_)%10 + 48);
fraction_ = fraction_/10;
//cout<<str<<endl;
}
//cout<<"String format: "<<str<<endl;
reverse(str2.begin(), str2.end());
str.append(str2);
cout<<"String representation: "<<str<<endl;
}
value_type fixed::value()
{
return value_;
}
value_type fixed::integer()
{
return integer_;
}
value_type fixed::fraction()
{
return fraction_;
}
fixed& fixed::operator+=(fixed other) // error
{ value_ += other.value();
return *this;
}
fixed operator+(fixed a, fixed b) //error
{ a+=b;
return a;}