我遇到了重载operator +和stream FuzzyNumber& FuzzyNumber::add(FuzzyNumber B){ FuzzyNumber fuzzyResult; fuzzyResult.setA(this -> getA() + B.getA() ); fuzzyResult.setB(this -> getB() + B.getB() ); fuzzyResult.setC(this -> getC() + B.getC() ); return fuzzyResult;}FuzzyNumber& operator+(FuzzyNumber& A, FuzzyNumber& B){ return A.add(B);}All fields inside class are double type. Here is overloaded ostream operator>>ostream& FuzzyNumber::streamWrite(ostream& outStream){ outStream << "( " << this -> getA() << ", " << this -> getB() << ", " << this -> getC() << ")"; return outStream;}ostream& operator<< (ostream& outStream, FuzzyNumber& fuzzyNumber){ fuzzyNumber.streamWrite(outStream); return outStream;}当我键入cout FuzzyNumber fuzzyNumber = numA + numB;cout << "A + B = " << fuzzyNumber << endl;其中numA和numB是FuzzyNumber类型。虽然当我用以下代码替换上面的行时程序停止运行:cout << "A + B = " << (numA + numB) << endl;也许默认的operator =有点问题,但是此类中没有动态变量,因此应该没有。预先感谢您的帮助! 最佳答案 在operator +内部,您返回了对堆栈变量的引用。您的编译器应该已经警告您此明显的实例。FuzzyNumber FuzzyNumber::add(FuzzyNumber B) const{ FuzzyNumber fuzzyResult; fuzzyResult.setA(this -> getA() + B.getA() ); fuzzyResult.setB(this -> getB() + B.getB() ); fuzzyResult.setC(this -> getC() + B.getC() ); return fuzzyResult;}FuzzyNumber operator+(const FuzzyNumber& A, const FuzzyNumber& B){ return A.add(B);}此代码应该可以解决您的问题。我还添加了一些适当的const正确性。关于c++ - 流过载和算术运算问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4197311/
10-10 22:58