我对我的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");}我删除了运算符(operator)*和运算符(operator)/,因为它们可以正常工作。我不知道我做错了什么,在发布这个问题之前,我已经一遍又一遍地研究了数学。是因为我没有使用指针吗?一个const?还是有所不同?先谢谢您的帮助! 最佳答案 这行是错误的: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) { ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~ live example如果您纠正上述错误,您的代码将起作用: 输出20/32 live example关于c++ - 如何修复分数类的重载+运算符的输出?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38560233/
10-12 06:30