我对我的fractionType类有疑问。我正在为分配编码,分配要求我重载基本算术运算符(+, - ,/,*)逻辑运算符(==,<,>,=<,=>)和系统运营商(<<,>>) 到目前为止,我有系统操作员,以及乘法和除法运算符。当我测试+和 - 运算符时,我的问题出现了。 我的输入被硬编码为2/4和1/8,但我的输出是3/8。这不对。
我的代码来自fractionType.cpp
#include <iostream>
#include "fractionType.h"
fractionType::fractionType(){
}
fractionType::fractionType(int a, int b) {
numerator = a;
denominator = b;
}
fractionType fractionType::operator+(fractionType fraction) {
fractionType anotherFraction;
if (denominator = fraction.denominator) {
anotherFraction.numerator = numerator + fraction.numerator;
anotherFraction.denominator = denominator;
}
if (denominator != fraction.denominator) {
anotherFraction.numerator = ((numerator) * (fraction.denominator)) + ((fraction.numerator) * (denominator));
anotherFraction.denominator = denominator * fraction.denominator;
}
return anotherFraction;
}
fractionType fractionType::operator-(fractionType fraction) {
fractionType anotherFraction;
if (denominator = fraction.denominator) {
anotherFraction.numerator = numerator - fraction.numerator;
anotherFraction.denominator = denominator;
}
else {
anotherFraction.numerator = (numerator * fraction.denominator) - (fraction.numerator * fraction.denominator);
anotherFraction.denominator = denominator * fraction.denominator;
}
return anotherFraction;
}
我的代码来自fractionType.h
#include <iostream>
class fractionType {
public:
fractionType(int a, int b);
fractionType();
fractionType operator*(fractionType fraction);
fractionType operator/(fractionType fraction);
fractionType operator+(fractionType fraction);
fractionType operator-(fractionType fraction);
friend std::ostream& operator<<(std::ostream& out, const fractionType &fraction) {
out << fraction.numerator << '/' << fraction.denominator;
return out;
}
friend std::istream& operator>> (std::istream& in, fractionType &fraction) {
char c;
in >> fraction.numerator >> c >> fraction.denominator;
return in;
}
private:
int numerator, denominator;
};
#endif FRACTIONTYPE_H
和我的source.cpp
#include <iostream>
#include "fractionType.h"
int main() {
fractionType aFraction(2, 4);
fractionType bFraction(1, 8);
fractionType cFraction;
cFraction = aFraction + bFraction;
std::cout << cFraction << std::endl;
system("PAUSE");
}
我切断了我的操作员*和操作员/,因为它们正常工作。 我不知道自己做错了什么,在发布这个问题之前,我一遍又一遍地重复数学。是因为我没有使用指针吗?一个常量?或者是不同的东西?在此先感谢您的帮助!
答案 0 :(得分:1)
这一行错了:
if (denominator = fraction.denominator) {
必须是
if (denominator == fraction.denominator) {
如果启用了警告,clang和gcc会告诉您,例如:
main.cpp:32:19: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if (denominator = fraction.denominator) {
~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
如果您更正了上述错误,则代码可以正常运行:
<强>输出强>
20/32