gpt4 book ai didi

c++ - 为什么我的成员函数不起作用?

转载 作者:行者123 更新时间:2023-12-03 09:03:01 25 4
gpt4 key购买 nike

我正在为计算机程序类编写计算机程序,但是由于某种原因,由于涉及成员函数的错误,我无法运行程序。我不断收到错误消息

“错误错误C3490:'den'无法修改,因为正在通过const对象访问它”

收到此消息我做错了什么,如何纠正它?

这是我的代码:

 // implement all class member functions here, gcd function is given

int Fraction::gcd()
{
if(num == 0) return 1;

int a = max(abs(num), abs(den));
int b = min(abs(num), abs(den));

while(b != 0)
{
int result = a%b;
a = b;
b = result;
}

return a;
}
void Fraction::input(istream& in)
{
char op;
in >> num;
in >> op;
in >> den;
if(den == 0)
{
cout << "Wrong input. Exit the program" << endl;
exit(1);
}
if(den < 0)
{
num *= -1;
den *= -1;}
}
void Fraction::output(ostream& out)
{
if(den == 0)
out << "0";
else
out << num << " / " << den;
}

Fraction::Fraction(int numerator, int denominator)
{
assert(denominator !=0);
num = numerator;
den = denominator;
if(den < 0)
{
num *=-1;
den *= -1;
}
}
bool Fraction::less(const Fraction& other) const
{
Fraction temp(other.num , other.den);
int num_1(num);
if(den != temp.den)
{
num_1 *= temp.den;
temp.num *= num;
}
if(num_1 < temp.num)
{return true;}
else
{return false;}
}
Fraction Fraction::reciprocal() const
{
Fraction tempa(num, den);
int temp(tempa.num);
tempa.num = tempa.den;
tempa.den = temp;
num = den;
if(den < 0)
{
num *= -1;
den *= -1;
}
return tempa;
}
Fraction Fraction::neg() const
{
num*=-1;
return;
}
Fraction::Fraction(int numerator)
{
num = numerator;
den = 1;
}
Fraction::Fraction()
{
num = 0;
den = 1;
}
Fraction Fraction::add(const Fraction& other) const
{
int num_1 = num *other.den;
int num_2 = den*other.den;
int denom = den*other.den;
Fraction result((num_1+num_2), denom);
result.reduce();
return result;
}
Fraction Fraction::div(const Fraction& other) const
{
Fraction temp(num, den);
other = other.reciprocal();
Fraction result(temp.mul(other));
return result;
}
Fraction Fraction::sub(const Fraction& other) const
{
int num_1 = num *other.den;
int num_2 = den*other.den;
int denom = den*other.den;
Fraction result((num_1-num_2), denom);
result.reduce();
return result;
}
Fraction Fraction::mul(const Fraction& other) const
{
int num_0 = num*other.num;
int denom = den*other.den;
Fraction result(num_0, denom);
result.reduce();
return result;
}
void Fraction::reduce()
{
int r = gcd();
num /= r;
den /= r;
if(num == 0)
den = 1;

}
bool Fraction::less_or_equal(const Fraction& other) const
{

}
bool Fraction::greater_or_equal(const Fraction& other) const
{

}
bool Fraction::equal(const Fraction& other) const
{

}
bool Fraction::not_equal(const Fraction& other) const
{

}
bool Fraction::greater(const Fraction& other)

最佳答案

您正在尝试在const方法中修改名为“den”的成员,并且无法在const内部进行任何修改,仅访问数据即可。您将需要修改函数以删除const或在不使用const的情况下复制它。

您的代码很难阅读,但这似乎发生在您的“reciprocal()”方法中。

关于c++ - 为什么我的成员函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21725364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com